package com.glela.order.service.impl.order;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.glela.api.pay.yeepay.component.YeePay;
import com.glela.api.pay.yeepay.model.YeePayDivideModel;
import com.glela.api.pay.yeepay.model.YeePayQueryDivideModel;
import com.glela.cache.model.RedisKey;
import com.glela.cache.redis.RedisKeys;
import com.glela.common.constant.BaseConstants;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.common.constant.CommonConstants;
import com.glela.common.constant.GoodsSelfTypeEnum;
import com.glela.common.constant.GoodsTypeEnum;
import com.glela.common.constant.OpenStoreTypeEnum;
import com.glela.common.constant.OrderStatusEnum;
import com.glela.common.constant.PayTypeEnum;
import com.glela.common.constant.SettlementStatusEnum;
import com.glela.common.constant.StatusEnum;
import com.glela.common.exception.LedgerAccounException;
import com.glela.common.exception.PayException;
import com.glela.common.exception.PlatformException;
import com.glela.common.util.Base64;
import com.glela.common.util.Config;
import com.glela.common.util.ExtendMethod;
import com.glela.common.util.HttpUtil;
import com.glela.common.util.JsonUtil;
import com.glela.common.util.ListUtils;
import com.glela.common.util.MD5;
import com.glela.common.util.NumberUtil;
import com.glela.common.util.OrderUtil;
import com.glela.company.model.CompanyXz;
import com.glela.company.model.XzOmsLog;
import com.glela.company.model.vo.CompanyXzVo;
import com.glela.company.service.CompanyService;
import com.glela.company.service.XzOmsLogService;
import com.glela.goods.mapper.GoodsExtendedAttributeMapper;
import com.glela.goods.model.GoodsCommission;
import com.glela.goods.model.GoodsExtends;
import com.glela.goods.model.LimitTimeSaleGoodsCommission;
import com.glela.goods.model.vo.InventoryVo;
import com.glela.mq.service.OrderQueueService;
import com.glela.order.mapper.OrderPayMapper;
import com.glela.order.mapper.OrderSettlementCommisionMapper;
import com.glela.order.mapper.OrderSettlementMapper;
import com.glela.order.model.Commision;
import com.glela.order.model.OrderDetail;
import com.glela.order.model.OrderInfo;
import com.glela.order.model.OrderObject;
import com.glela.order.model.OrderPay;
import com.glela.order.model.OrderSettlement;
import com.glela.order.model.OrderSettlementCommision;
import com.glela.order.model.PayTypeConfig;
import com.glela.order.model.UserCommision;
import com.glela.order.model.UserNormalCommision;
import com.glela.order.model.request.RequestOrderDetail;
import com.glela.order.model.response.ResponseGetOrderObject;
import com.glela.order.service.CommissionService;
import com.glela.order.service.impl.AbstractOrderServiceImpl;
import com.glela.order.vo.OpenStorePriceVo;
import com.glela.order.vo.OrderDetailVo;
import com.glela.order.vo.OrderForThirdResponseXzResult;
import com.glela.order.vo.OrderForXZOMSVo;
import com.glela.order.vo.OrderForXZTeacherVo;
import com.glela.order.vo.OrderInfoVo;
import com.glela.order.vo.OrderSettlementVo;
import com.glela.order.vo.ParamsCommisionVo;
import com.glela.order.vo.PayInfoForXZOMSVo;
import com.glela.order.vo.ProductForXZOMSVo;
import com.glela.order.vo.PromotionForXZOMSVo;
import com.glela.order.vo.PublicForXZOMSVo;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.OperationLogMapper;
import com.glela.platform.mapper.UserJournalMapper;
import com.glela.platform.mapper.UserPointJournalMapper;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.CUserPointTransaction;
import com.glela.platform.model.OperationLog;
import com.glela.platform.model.TalentJob;
import com.glela.platform.model.User;
import com.glela.platform.model.UserAddress;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.UserJournal;
import com.glela.platform.model.UserPointJournal;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.TalentJobSerice;
import com.glela.platform.vo.GoodsSimpleVo;
import com.glela.platform.vo.ParamsUserXzbTransactionVo;

/**
 * @author liujie
 * @2016年10月25日
 */
@Service("orderService2")
@Order(2)
public class OrderServiceImpl2 extends AbstractOrderServiceImpl {
	private static Logger logger = LoggerFactory.getLogger(OrderServiceImpl2.class);
	@Autowired
	private TalentJobSerice talentJobSerice;
	@Autowired
	protected CompanyService companyService;
	@Autowired
	protected OrderPayMapper orderPayMapper;
	@Autowired
	protected OrderSettlementMapper orderSettlementMapper;
	@Autowired
	private XzOmsLogService xzOmsLogService;
	@Autowired
	private OperationLogMapper operationLogMapper;
	@Autowired
	private OrderSettlementCommisionMapper orderSettlementCommisionMapper;
	@Autowired
	private UserPointJournalMapper userPointJournalMapper;
	@Autowired
	private CommissionService commissionService;
	@Autowired
	private UserJournalMapper userJournalMapper;
	@Autowired
	private OrderQueueService orderQueueService;
	@Autowired
	private GoodsExtendedAttributeMapper goodsExtendedAttributeMapper;
	
	@Override
	public void updateOrderForXZOMS(String orderObjectOrderSn, String payId, Integer payType, String t_id) throws PlatformException {
		String orderInfoSn = "";
		String result = "";
		try {
			boolean isReturn = false;
			int giftNum = 0;
			
			//支付方式
			String xzPayType = "WX";
			if (payType.intValue() == PayTypeEnum.T2.getCode().intValue()) {
				xzPayType = "ALIPAY";
			} else if (payType.intValue() >= PayTypeEnum.T20.getCode().intValue() && payType.intValue() <= PayTypeEnum.T24.getCode().intValue()) {
				xzPayType = "YB";
			}
			
			//父订单
			OrderObject orderObject= orderObjectMapper.selectByOrderSn(orderObjectOrderSn);
			//所有支付成功的子订单
			List<OrderInfoVo> orderInfoList = orderDao.selectOrderInfoVoByStatusOrderObjectSn(orderObjectOrderSn, OrderStatusEnum.S2.getCode());
			//所有支付成功的明细订单
			List<OrderDetailVo> orderDetailVoList = orderDao.selectOrderDetailByStatusOrderObjectSn(orderObjectOrderSn, OrderStatusEnum.S2.getCode());
			Map<Long,OrderDetailVo> orderDetailMap=new HashMap<>();
			for(OrderDetailVo  Vo:orderDetailVoList){
				orderDetailMap.put(Vo.getId(),Vo);
			}

			//查询分账信息 设置分账公司
			List<OrderSettlementVo> OrderSettlementDetailList = orderSettlementMapper.selectByOrderSnForSettlementDetail(orderObjectOrderSn);
			CompanyXzVo companyXz = null;
			if(orderInfoList!=null&&orderInfoList.size()>0&&StringUtils.isNotBlank(orderInfoList.get(0).getJobNo())){
				int CompanyId=orderInfoList.get(0).getCompanyId();
				String JobNo=orderInfoList.get(0).getJobNo();
				 companyXz=companyService.selectBycompany_Id(CompanyId);
				 companyXz.setJobNo(JobNo);
			}
			if(companyXz==null||StringUtils.isBlank(companyXz.getCompanyAccount())||StringUtils.isBlank(companyXz.getManagerAccount())){
				logger.error("未找到公司,相关订单 {}",orderObject.getOrderSn());
				return;
			}
			
			//验证结算单金额是否和父订单保持一致
			int SettlementFee=0;
			int SettlementCoin=0;
			int SettlementBalance=0;
			int redpackage=0;
			for (OrderSettlementVo orderSettlement : OrderSettlementDetailList) {
				SettlementFee+=orderSettlement.getTotalFee();
				SettlementCoin+=orderSettlement.getCashCoin();
				SettlementBalance+=orderSettlement.getBalancePaid();
				redpackage+=orderDetailMap.get(orderSettlement.getOrderDetailId()).getRedPacketFee().intValue();
			}
			if(redpackage!=orderObject.getRedPacketFee().intValue()||SettlementFee!=orderObject.getTotalFee()||SettlementCoin!=orderObject.getCashCoin()||SettlementBalance!=orderObject.getBalancePaid()){
				throw new PlatformException("推送订单失败: orderObjectOrderSn :" + orderObjectOrderSn + " --------结算单金额和订单金额不一致");
			}
			
			/*if(orderObject.getOpenStore()==1&&!StringUtils.equals(xzPayType, "YB")){
				throw new PlatformException("推送订单失败: orderObjectOrderSn :" + orderObjectOrderSn + " --------开店单不是易宝支付");
			}*/
			/*判断是否是开店单  开店单必须等订单分账完成之后才能退单到oms begin*/
			if(orderObject.getOpenStore()==1&&StringUtils.equals(xzPayType, "YB")){//是开店单 并且是易宝支付
				//查找开店商品
				OrderDetailVo openStoreOrderDetailVo=null;
				//开店商品数量 种类只能是一个
				int openStoreNum=0;
				for(OrderDetailVo Vo:orderDetailVoList){
					if(Vo.getIsOpenStoreGoods()==1){//开店单的开店商品
					   openStoreOrderDetailVo=Vo;
					   openStoreNum+=openStoreOrderDetailVo.getQuantity();
					}
				}
				if(openStoreNum!=1||openStoreOrderDetailVo==null){
					throw new PlatformException("开店商品数量错误 订单号:"+orderObject.getOrderSn()+" 数量:"+openStoreNum);
				}
				for (OrderSettlementVo orderSettlement : OrderSettlementDetailList) {
					if(orderSettlement.getOrderDetailId()==openStoreOrderDetailVo.getId().longValue()){
						if(!(StringUtils.isNotBlank(orderSettlement.getCompanyAccount())&&
								StringUtils.isNotBlank(orderSettlement.getManagerAccount()))){
							throw new PlatformException("开店单未分账,分账结束后在推单 订单号:"+orderObject.getOrderSn());
						}
					}
				}
			}
			/*判断是否是开店单  开店单必须等订单分账完成之后才能退单到oms end*/
			
			
			Map<Long, List<OrderDetailVo>> orderDetailVoMap = new HashMap<Long, List<OrderDetailVo>>();// 以订单id归类商品明细
			Map<Long, Integer> quantityMap = new HashMap<Long, Integer>();// 以订单id统计订单商品总个数
			Map<Long, OrderDetailVo> orderDetailVoInventoryMap = new HashMap<Long, OrderDetailVo>();
			int applywelfareId = 0;
			GoodsExtends goodsExtends = null;//判断海外购信息
			for (OrderDetailVo orderDetail : orderDetailVoList) {
				GoodsExtends tgoodsExtends = goodsExtendedAttributeMapper.selectExtendsAttrByGoodsID(orderDetail.getGoodId());
				if (tgoodsExtends != null && tgoodsExtends.getOverseasGoods() == 1) {// 是海外购
					goodsExtends=tgoodsExtends;
					break;
				}
			}
			for (OrderDetailVo orderDetailVo : orderDetailVoList) {
				if (CollectionUtils.isEmpty(orderDetailVoMap.get(orderDetailVo.getOrderId()))) {
					orderDetailVoMap.put(orderDetailVo.getOrderId(), new ArrayList<OrderDetailVo>());
				}
				if (quantityMap.get(orderDetailVo.getOrderId()) == null) {
					quantityMap.put(orderDetailVo.getOrderId(), 0);
				}
				orderDetailVoMap.get(orderDetailVo.getOrderId()).add(orderDetailVo);
				quantityMap.put(orderDetailVo.getOrderId(), quantityMap.get(orderDetailVo.getOrderId()).intValue() + orderDetailVo.getQuantity());
				applywelfareId = orderDetailVo.getApplywelfareId();
				orderDetailVoInventoryMap.put(orderDetailVo.getInventoryId(), orderDetailVo);
			}
			boolean pushOmsSuccess=true;
			//自营、非自营店订单数
			int megerStoreNum = 0;
			for (OrderInfoVo orderInfo : orderInfoList) {
				if (orderInfo.getStoreId() != null && (orderInfo.getStoreId() == 13 || orderInfo.getStoreId() == 14)) {
					megerStoreNum++;
				}
			}
			boolean megerOrder = megerStoreNum > 1;//是否合单
			for (OrderInfoVo orderInfoVo : orderInfoList) {
				orderInfoVo.setMobile(StringUtils.stripToEmpty(orderInfoVo.getMobile()));

				orderInfoSn = orderInfoVo.getOrderSn();
				OrderForXZOMSVo orderForXZOMSVo = new OrderForXZOMSVo();
				orderForXZOMSVo.setP_id(orderObjectOrderSn);
				//需合并发货
				if (megerOrder) {
					orderForXZOMSVo.setMerge_order((orderInfoVo.getStoreId() == 13 || orderInfoVo.getStoreId() == 14));
				} else {
					orderForXZOMSVo.setMerge_order(megerOrder);
				}
				orderForXZOMSVo.setT_id(t_id);
				orderForXZOMSVo.setOrderPay_id(t_id);//支付单号
				//新增店铺ID---------zhangrenjie  2017年10月13日
				orderForXZOMSVo.setChannel_store_id(orderInfoVo.getStoreId());
				orderForXZOMSVo.setChannel_order_id(orderInfoVo.getOrderSn());
				orderForXZOMSVo.setChannel_type(applywelfareId > 0 ? "2" : "2");
				orderForXZOMSVo.setPaid_status("4444");
				orderForXZOMSVo.setConsignee_name(orderInfoVo.getLinkMan());
				orderForXZOMSVo.setConsignee_mobile("");
				orderForXZOMSVo.setConsignee_phone("");
				if (StringUtils.isNotBlank(orderInfoVo.getMobile())) {
					if (StringUtils.startsWith(orderInfoVo.getMobile(), "1") && StringUtils.length(orderInfoVo.getMobile()) == 11) {
						orderForXZOMSVo.setConsignee_mobile(orderInfoVo.getMobile());
					} else {//不是手机号是座机
						orderForXZOMSVo.setConsignee_phone(orderInfoVo.getMobile());
					}
				}
				orderForXZOMSVo.setChannel_source("3006");
				orderForXZOMSVo.setConsignee_province_name(orderInfoVo.getProvince());
				orderForXZOMSVo.setConsignee_city_name(orderInfoVo.getCity());
				orderForXZOMSVo.setConsignee_region_name(orderInfoVo.getArea());
				orderForXZOMSVo.setConsignee_address(orderInfoVo.getAddress());
				orderForXZOMSVo.setTotal_fee(orderInfoVo.getTotalPrice().floatValue() / 100);
				orderForXZOMSVo.setFreight_amount(orderInfoVo.getFreight().floatValue() / 100);
				orderForXZOMSVo.setPaid_amount((orderInfoVo.getTotalPrice().floatValue()) / 100 - ((float) orderInfoVo.getPromotionDiscount()) / 100 - (float) orderInfoVo.getoActivDiscountFee() / 100 - (float) orderInfoVo.getRedPacketFee() / 100 + orderForXZOMSVo.getFreight_amount());
				orderForXZOMSVo.setPaid_amount(Float.parseFloat(CommonConstants.df2.format(orderForXZOMSVo.getPaid_amount())));
				orderForXZOMSVo.setCash_paid_amount(Float.parseFloat(CommonConstants.df2.format(orderForXZOMSVo.getPaid_amount() - (float) orderInfoVo.getCashCoin() / 100 - (float) orderInfoVo.getBalancePaid() / 100)));
				orderForXZOMSVo.setAccount_paid_amount((float) orderInfoVo.getCashCoin() / 100);
				orderForXZOMSVo.setBalance_paid_amount((float) orderInfoVo.getBalancePaid() / 100);
				orderForXZOMSVo.setQuantity(quantityMap.get(orderInfoVo.getId()));
				orderForXZOMSVo.setCreate_time(orderInfoVo.getCreateTime().substring(0, orderInfoVo.getCreateTime().length() - 2));
				
				//海外购订单封装身份证信息 ZYF 2018.04.24
				if(goodsExtends!=null) {//是海外购订单
					Integer _userAddressId = orderInfoVo.getMemberDeliveryAddressId();
					UserAddress _userAddress = userAddressService.selectUserAddressById(_userAddressId == null ? 0l : _userAddressId.longValue());
					if(_userAddress != null && !StringUtils.isBlank(_userAddress.getIdNumber())) {
						orderForXZOMSVo.setResident_identity_card(_userAddress.getIdNumber());
					}
				}
				if (org.apache.commons.lang3.StringUtils.isBlank(orderInfoVo.getPayTime())) {
					orderForXZOMSVo.setPay_time(null);
				} else {
					orderForXZOMSVo.setPay_time(orderInfoVo.getPayTime().substring(0, orderInfoVo.getPayTime().length() - 2));
				}
				List<OrderSettlementVo> orderSettlementList = selectByOrderSnForSettlementDetail(orderObjectOrderSn);
				ResponseUser openUser = userService.selectUserRoleById(orderInfoVo.getOpenStoreUserId());
				orderForXZOMSVo.setIs_first(orderInfoVo.getOpenStore());
				if (openUser != null) {
					orderForXZOMSVo.setShop_classify(openUser.getLevel() == CommonConstants.TALENT_TEACHER_LEVEL ? "讲师店" : "学生店");
				}
				if (companyXz != null) {
					orderForXZOMSVo.setOperator_no(companyXz.getJobNo());
				}
				Map<Long, OrderSettlementVo> orderSettlementMap = new HashMap<Long, OrderSettlementVo>();
				Map<String, OrderSettlementVo> orderSettlementMap2 = new HashMap<String, OrderSettlementVo>();
				for (OrderSettlementVo orderSettlementVo : orderSettlementList) {
					if (orderSettlementVo.getGoodsType().intValue() == GoodsTypeEnum.T0.getCode()) {//目前没有c区产品了
						if (orderSettlementVo.getSelfSupport().intValue() == GoodsSelfTypeEnum.T1.getCode()) {
							orderSettlementVo.setCompanyAccount(Config.getString("xz.yeepay.yzAccount"));
						} else {
							if (companyXz != null) {
								orderSettlementVo.setCompanyAccount(companyXz.getCompanyAccount());
								orderSettlementVo.setManagerAccount(companyXz.getManagerAccount());
							} else {
								orderSettlementVo.setCompanyAccount(Config.getString("xz.yeepay.whAccount"));
								orderSettlementVo.setManagerAccount(Config.getString("xz.yeepay.whManagerAccount"));
							}
						}
					} else {
						if (orderSettlementVo.getSelfSupport().intValue() == GoodsSelfTypeEnum.T1.getCode()) {
							orderSettlementVo.setCompanyAccount(Config.getString("xz.yeepay.yzAccount"));
						} else {
							if (companyXz != null) {
								orderSettlementVo.setCompanyAccount(companyXz.getCompanyAccount());
								orderSettlementVo.setManagerAccount(companyXz.getManagerAccount());
							}
						}
					}
					orderSettlementMap.put(orderSettlementVo.getOrderDetailId(), orderSettlementVo);
					orderSettlementMap2.put(orderSettlementVo.getOrderSn(), orderSettlementVo);
				}
				OrderSettlementVo orderSettlementVoTmp = orderSettlementMap2.get(orderInfoSn);
				if (orderSettlementVoTmp != null && orderSettlementVoTmp.getCompanyAccount() != null) {
					if (orderSettlementVoTmp.getCompanyAccount().equals(Config.getString("xz.yeepay.yzAccount"))) {
						orderForXZOMSVo.setCompany_id(Config.getString("xz.yeepay.yzId"));
						orderForXZOMSVo.setCompany_name(Config.getString("xz.yeepay.yzName"));
					} else if (orderSettlementVoTmp.getCompanyAccount().equals(Config.getString("xz.yeepay.whAccount"))) {
						orderForXZOMSVo.setCompany_id(Config.getString("xz.yeepay.whId"));
						orderForXZOMSVo.setCompany_name(Config.getString("xz.yeepay.whName"));
					} else if (companyXz != null) {
						orderForXZOMSVo.setCompany_id(companyXz.getBranchId());
						orderForXZOMSVo.setCompany_name(companyXz.getCompanyName());
					}
					if(ArrayUtils.contains(new int[]{1,2,3}, orderInfoVo.getPayType().intValue())) {//直连支付
						BaseRestrictions base=
							baseRestrictionsService.getBaseRestrictionsForCache("直连支付记账公司");
						if(base!=null){
							orderForXZOMSVo.setCompany_id(base.getName());
							orderForXZOMSVo.setCompany_name(base.getRealName());
						}
					}
				}
				//记账公司
				orderForXZOMSVo.setJzgs_id(orderForXZOMSVo.getCompany_id());
				orderForXZOMSVo.setJzgs_name(orderForXZOMSVo.getCompany_name());
				//讲师所属公司
				orderForXZOMSVo.setCompany_id(companyXz.getBranchId());
				orderForXZOMSVo.setCompany_name(companyXz.getCompanyName());
				List<ProductForXZOMSVo> productList = new ArrayList<ProductForXZOMSVo>();
				List<ProductForXZOMSVo> freightList = new ArrayList<ProductForXZOMSVo>();
				boolean isGift = false;
				Map<Long, PromotionForXZOMSVo> orderInfoActivMap = new LinkedHashMap<>();
				//明细单
				for (OrderDetailVo orderDetailVo : orderDetailVoMap.get(orderInfoVo.getId())) {
					orderForXZOMSVo.setShop_type(orderDetailVo.getGoodsType() == GoodsTypeEnum.T1.getCode() ? "B" : "C");
					ProductForXZOMSVo productForXZOMSVo = new ProductForXZOMSVo();
					productForXZOMSVo.setTotal_amount(orderDetailVo.getTotalPrice().floatValue() / 100);
					productForXZOMSVo.setSale_price(orderDetailVo.getSalePrice().floatValue() / 100);
					productForXZOMSVo.setProduct_name(orderDetailVo.getBrandName() + " " + orderDetailVo.getGoodName() + " " + orderDetailVo.getSpecName());
					productForXZOMSVo.setProduct_type("normal");
					productForXZOMSVo.setProduct_nums(orderDetailVo.getQuantity());
					productForXZOMSVo.setNormal_price(((Integer) orderDetailVo.getSuggestedPrice()).floatValue() / 100);
					productForXZOMSVo.setProduct_sn(orderDetailVo.getProductBn());
					productForXZOMSVo.setDiscount_fee(((float) orderDetailVo.getPromotionDiscount()) / 100);
					productForXZOMSVo.setPay_no(payId);
					productForXZOMSVo.setIs_gift(orderDetailVo.getIsGift() != null && orderDetailVo.getIsGift() == 1);
					productForXZOMSVo.setIs_limit_sale(orderDetailVo.getLimitTimeSaleId()!= null &&orderDetailVo.getLimitTimeSaleId()>0);
					productForXZOMSVo.setChannel_order_row_id(orderDetailVo.getId());
					if (orderDetailVo.getoActivId() > 0 && orderDetailVo.getoActivDiscountFee() > 0) {
						PromotionForXZOMSVo promotionForXZOMSVo = orderInfoActivMap.get(orderDetailVo.getoActivId());
						if (promotionForXZOMSVo == null) {
							promotionForXZOMSVo = new PromotionForXZOMSVo();
							orderInfoActivMap.put(orderDetailVo.getoActivId(), promotionForXZOMSVo);

							promotionForXZOMSVo.setDiscount_fee(0f);
							promotionForXZOMSVo.setPromotion_id(orderDetailVo.getoActivId() + "");
							promotionForXZOMSVo.setPromotion_name("");
							promotionForXZOMSVo.setPromotion_desc("活动");
							promotionForXZOMSVo.setPromotion_type("7105");
						}
						promotionForXZOMSVo.setDiscount_fee(promotionForXZOMSVo.getDiscount_fee() + orderDetailVo.getoActivDiscountFee());
					}

					if (xzPayType.equals("YB")) {
						if (orderSettlementMap.get(orderDetailVo.getId()).getCashCoinDealer().intValue() > 0) {
							productForXZOMSVo.setLedger_cmycoin_no(orderSettlementMap.get(orderDetailVo.getId()).getCompanyAccount());
							productForXZOMSVo.setLedger_cmycoin_amount((((double) orderSettlementMap.get(orderDetailVo.getId()).getCashCoinDealer()) / 100) + "");
						}
						if (orderSettlementMap.get(orderDetailVo.getId()).getBalancePaidDealer().intValue() > 0) {
							productForXZOMSVo.setLedger_cmybalance_no(orderSettlementMap.get(orderDetailVo.getId()).getCompanyAccount());
							productForXZOMSVo.setLedger_cmybalance_amount((((double) orderSettlementMap.get(orderDetailVo.getId()).getBalancePaidDealer()) / 100) + "");
						}
						productForXZOMSVo.setLedger_co_no(orderSettlementMap.get(orderDetailVo.getId()).getCompanyAccount());
						productForXZOMSVo.setLedger_co_amount((((double) orderSettlementMap.get(orderDetailVo.getId()).getSettlementPriceDealer()) / 100) + "");
						productForXZOMSVo.setLedger_co_ratio((((double) orderSettlementMap.get(orderDetailVo.getId()).getSettlementRateDealer()) / 100) + "");
						if (orderSettlementMap.get(orderDetailVo.getId()).getManagerAccount() != null && !orderSettlementMap.get(orderDetailVo.getId()).getManagerAccount().isEmpty()) {
							if (orderSettlementMap.get(orderDetailVo.getId()).getCashCoinManager() > 0) {
								productForXZOMSVo.setLedger_corpcoin_no(orderSettlementMap.get(orderDetailVo.getId()).getManagerAccount());
								productForXZOMSVo.setLedger_corpcoin_amount((((double) orderSettlementMap.get(orderDetailVo.getId()).getCashCoinManager()) / 100) + "");
							}
							if (orderSettlementMap.get(orderDetailVo.getId()).getBalancePaidManager() > 0) {
								productForXZOMSVo.setLedger_corpbalance_no(orderSettlementMap.get(orderDetailVo.getId()).getManagerAccount());
								productForXZOMSVo.setLedger_corpbalance_amount((((double) orderSettlementMap.get(orderDetailVo.getId()).getBalancePaidManager()) / 100) + "");
							}
							productForXZOMSVo.setLedger_corp_no(orderSettlementMap.get(orderDetailVo.getId()).getManagerAccount());
							productForXZOMSVo.setLedger_corp_amount((((double) orderSettlementMap.get(orderDetailVo.getId()).getSettlementPriceManager()) / 100) + "");
							productForXZOMSVo.setLedger_corp_ratio((((double) orderSettlementMap.get(orderDetailVo.getId()).getSettlementRateManager()) / 100) + "");
						}
					} else {
						//非易宝方式直接把经销商和代理商设为空
						productForXZOMSVo.setLedger_co_no(null);
						productForXZOMSVo.setLedger_corp_no(null);
						productForXZOMSVo.setLedger_cmycoin_no(Config.getString("xz.yeepay.yzAccount"));
						productForXZOMSVo.setLedger_cmycoin_amount((((double) orderDetailVo.getCashCoin()) / 100) + "");
						productForXZOMSVo.setLedger_cmybalance_no(Config.getString("xz.yeepay.yzAccount"));
						productForXZOMSVo.setLedger_cmybalance_amount((((double) orderDetailVo.getBalancePaid()) / 100) + "");
					}
					productForXZOMSVo.setPayment(((float) orderDetailVo.getTotalFee()) / 100);
					productList.add(productForXZOMSVo);
					if (orderDetailVo.getSelfSupport() == GoodsSelfTypeEnum.T1.getCode()) {
						isGift = true;
					}
				}
				//添加运费的分账信息
				for(OrderSettlementVo Vo:orderSettlementList){
					if(Vo.getOrderDetailId()!=null&&Vo.getOrderDetailId().longValue()<0&&orderInfoVo.getId()!=null&&
							orderInfoVo.getId().longValue()==0L-Vo.getOrderDetailId().longValue()){//找到运费分账信息
						orderForXZOMSVo.setShop_type("B");
						ProductForXZOMSVo productForXZOMSVo = new ProductForXZOMSVo();
						productForXZOMSVo.setProduct_name("虚拟物品 运费清账");
						productForXZOMSVo.setProduct_type("normal");
						productForXZOMSVo.setProduct_nums(1);
						productForXZOMSVo.setCash_coin((((double)Vo.getCashCoin()) / 100) + "");
						productForXZOMSVo.setBalance_paid((((double)Vo.getBalancePaid()) / 100) + "");
						productForXZOMSVo.setTotal_fee((((double)Vo.getTotalFee()) / 100) + "");
						if (Vo.getCashCoinDealer().intValue() > 0) {
							productForXZOMSVo.setLedger_cmycoin_no(Vo.getCompanyAccount());
							productForXZOMSVo.setLedger_cmycoin_amount((((double)Vo.getCashCoinDealer()) / 100) + "");
						}
						if (Vo.getBalancePaidDealer().intValue() > 0) {
							productForXZOMSVo.setLedger_cmybalance_no(Vo.getCompanyAccount());
							productForXZOMSVo.setLedger_cmybalance_amount((((double)Vo.getBalancePaidDealer()) / 100) + "");
						}
						productForXZOMSVo.setLedger_co_no(Vo.getCompanyAccount());
						productForXZOMSVo.setLedger_co_amount((((double)Vo.getSettlementPriceDealer()) / 100) + "");
						productForXZOMSVo.setLedger_co_ratio((((double)Vo.getSettlementRateDealer()) / 100) + "");
						if (Vo.getManagerAccount() != null && !Vo.getManagerAccount().isEmpty()) {
							if (Vo.getCashCoinManager() > 0) {
								productForXZOMSVo.setLedger_corpcoin_no(Vo.getManagerAccount());
								productForXZOMSVo.setLedger_corpcoin_amount((((double)Vo.getCashCoinManager()) / 100) + "");
							}
							if (Vo.getBalancePaidManager() > 0) {
								productForXZOMSVo.setLedger_corpbalance_no(Vo.getManagerAccount());
								productForXZOMSVo.setLedger_corpbalance_amount((((double)Vo.getBalancePaidManager()) / 100) + "");
							}
							productForXZOMSVo.setLedger_corp_no(Vo.getManagerAccount());
							productForXZOMSVo.setLedger_corp_amount((((double)Vo.getSettlementPriceManager()) / 100) + "");
							productForXZOMSVo.setLedger_corp_ratio((((double)Vo.getSettlementRateManager()) / 100) + "");
						}
						freightList.add(productForXZOMSVo);
						break;
					}
				}
				//添加首单礼的赠品
				if (isGift) {
					// 判断订单是首单，且
					if (orderForXZOMSVo.getIs_first() == OpenStoreTypeEnum.T1.getCode() && orderDetailVoInventoryMap.get(Long.valueOf(Config.getString("gift.validInventoryId"))) != null) {
						long inventoryId = Long.valueOf(Config.getString("gift.inventoryId"));
						InventoryVo inventoryVo = goodsService.selectInventoryById(inventoryId);
						giftNum = inventoryVo.getInventoryNum();
						int inResult = orderDao.subInventoryNumById(inventoryId, 1);
						if (inResult > 0) {
							ProductForXZOMSVo productForXZOMSVo = new ProductForXZOMSVo();
							productForXZOMSVo.setTotal_amount(0);
							productForXZOMSVo.setSale_price(0);
							productForXZOMSVo.setProduct_name(inventoryVo.getBrandName() + " " + inventoryVo.getGoodName() + " " + inventoryVo.getSpecName());
							productForXZOMSVo.setProduct_type("normal");
							productForXZOMSVo.setProduct_nums(1);
							productForXZOMSVo.setNormal_price(0);
							productForXZOMSVo.setProduct_sn(inventoryVo.getProductBn());
							productForXZOMSVo.setDiscount_fee(0);
							productForXZOMSVo.setPay_no(payId);
							productForXZOMSVo.setPayment(0);
							productForXZOMSVo.setLedger_cmycoin_no(Config.getString("xz.yeepay.yzAccount"));
							productForXZOMSVo.setLedger_cmycoin_amount("0");
							productForXZOMSVo.setLedger_cmybalance_no(Config.getString("xz.yeepay.yzAccount"));
							productForXZOMSVo.setLedger_cmybalance_amount("0");
							productList.add(productForXZOMSVo);
							orderForXZOMSVo.setQuantity(orderForXZOMSVo.getQuantity() + 1);
						} else {
							throw new PlatformException("推送订单失败: orderObjectOrderSn :" + orderObjectOrderSn + " --------添加赠品失败, 原因是扣减更新赠品库存失败 inventoryId=" + inventoryId);
						}
					}
				}
				orderForXZOMSVo.setProducts(productList);
				orderForXZOMSVo.setFreights(freightList);
				//封装优惠券信息
				if (orderInfoVo.getPromotionId().intValue() > 0) {
					PromotionForXZOMSVo promotionForXZOMSVo = new PromotionForXZOMSVo();
					promotionForXZOMSVo.setPromotion_id(orderInfoVo.getPromotionId() + "");
					promotionForXZOMSVo.setPromotion_name("");
					promotionForXZOMSVo.setDiscount_fee(((float) orderInfoVo.getPromotionDiscount()) / 100);
					promotionForXZOMSVo.setPromotion_desc("优惠券");
					promotionForXZOMSVo.setPromotion_type("7104");

					if (orderForXZOMSVo.getPromotion_details() == null) {
						orderForXZOMSVo.setPromotion_details(new ArrayList<PromotionForXZOMSVo>());
					}
					orderForXZOMSVo.getPromotion_details().add(promotionForXZOMSVo);
				}
				//封装红包信息
				if (orderInfoVo.getRedPacketId().intValue()> 0) {
					PromotionForXZOMSVo promotionForXZOMSVo = new PromotionForXZOMSVo();
					promotionForXZOMSVo.setPromotion_id(orderInfoVo.getRedPacketId() + "");
					promotionForXZOMSVo.setPromotion_name("");
					promotionForXZOMSVo.setDiscount_fee(((float) orderInfoVo.getRedPacketFee()) / 100);
					promotionForXZOMSVo.setPromotion_desc("红包");
					promotionForXZOMSVo.setPromotion_type("7104");

					if (orderForXZOMSVo.getPromotion_details() == null) {
						orderForXZOMSVo.setPromotion_details(new ArrayList<PromotionForXZOMSVo>());
					}
					orderForXZOMSVo.getPromotion_details().add(promotionForXZOMSVo);
				}
				//封装活动信息
				if (MapUtils.isNotEmpty(orderInfoActivMap)) {
					if (CollectionUtils.isEmpty(orderForXZOMSVo.getPromotion_details())) {
						orderForXZOMSVo.setPromotion_details(new LinkedList<PromotionForXZOMSVo>());
					}
					for (Long activId : orderInfoActivMap.keySet()) {
						PromotionForXZOMSVo promotionActiv = orderInfoActivMap.get(activId);
						promotionActiv.setDiscount_fee(NumberUtils.toFloat(CommonConstants.FORMAT_YUAN.format(promotionActiv.getDiscount_fee() / 100), 0));
						orderForXZOMSVo.getPromotion_details().add(promotionActiv);
					}
				}

				//封装支付流水
				List<PayInfoForXZOMSVo> payInfoList = new ArrayList<PayInfoForXZOMSVo>();
				orderForXZOMSVo.setPay_info(payInfoList);
				float cashCoin = (float) orderInfoVo.getCashCoin() / 100;
				float balancePaid = (float) orderInfoVo.getBalancePaid() / 100;
				if (orderInfoVo.getTotalFee() > 0) {
					OrderPay selectByPaySn = orderPayMapper.selectByPaySn(t_id);
					if (selectByPaySn != null && selectByPaySn.getStatus() == 1) {
						PayInfoForXZOMSVo payInfoForXZOMSVo = new PayInfoForXZOMSVo();
						payInfoForXZOMSVo.setPay_amt(Float.parseFloat(CommonConstants.df2.format(1f * orderInfoVo.getTotalFee() / 100)));
						switch (selectByPaySn.getPayType()) {
							//微信
							case 1:
							case 3:
								payInfoForXZOMSVo.setPay_type("WX");
								break;
							//支付宝
							case 2:
								payInfoForXZOMSVo.setPay_type("ALIPAY");
								break;
							//易宝
							case 20:
							case 21:
							case 22:
							case 23:
							case 24:
								payInfoForXZOMSVo.setPay_type("YB");
								break;

							default:
								break;
						}
						payInfoForXZOMSVo.setPay_time(StringUtils.substring(orderInfoVo.getPayTime(), 0, 19));
						payInfoForXZOMSVo.setPay_no(payId);
						payInfoForXZOMSVo.setPay_number(t_id);
						payInfoList.add(payInfoForXZOMSVo);
					}
				}
				if (orderInfoVo.getCashCoin() > 0) {//封装妆币支付
					PayInfoForXZOMSVo payInfoForXZOMSVoXZB = new PayInfoForXZOMSVo();
					payInfoForXZOMSVoXZB.setPay_amt(cashCoin);
					payInfoForXZOMSVoXZB.setPay_type("XZB");
					if (StringUtils.isEmpty(orderInfoVo.getPayTime())) {
						payInfoForXZOMSVoXZB.setPay_time(StringUtils.substring(orderInfoVo.getCreateTime(), 0, 19));
					} else {
						payInfoForXZOMSVoXZB.setPay_time(StringUtils.substring(orderInfoVo.getPayTime(), 0, 19));
					}
					payInfoForXZOMSVoXZB.setPay_no(payId);
					payInfoForXZOMSVoXZB.setPay_number(t_id);
					payInfoList.add(payInfoForXZOMSVoXZB);
				}
				if (orderInfoVo.getBalancePaid() > 0) {//封装余额支付
					PayInfoForXZOMSVo payInfoForXZOMSVoCommission = new PayInfoForXZOMSVo();
					payInfoForXZOMSVoCommission.setPay_amt(balancePaid);
					payInfoForXZOMSVoCommission.setPay_type("COMMISSION");
					if (StringUtils.isEmpty(orderInfoVo.getPayTime())) {
						payInfoForXZOMSVoCommission.setPay_time(StringUtils.substring(orderInfoVo.getCreateTime(), 0, 19));
					} else {
						payInfoForXZOMSVoCommission.setPay_time(StringUtils.substring(orderInfoVo.getPayTime(), 0, 19));
					}
					payInfoForXZOMSVoCommission.setPay_no(payId);
					payInfoForXZOMSVoCommission.setPay_number(t_id);
					payInfoList.add(payInfoForXZOMSVoCommission);
				}
				//				}
				//0元支付订单补一个0元支付流水
				if (payInfoList.size() == 0 && orderInfoVo.getTotalFee() == 0 && orderInfoVo.getBalancePaid() == 0 && orderInfoVo.getCashCoin() == 0) {
					PayInfoForXZOMSVo zeroPayInfo = new PayInfoForXZOMSVo();
					zeroPayInfo.setPay_amt(0);
					zeroPayInfo.setPay_type("YB");
					if (StringUtils.isEmpty(orderInfoVo.getPayTime())) {
						zeroPayInfo.setPay_time(StringUtils.substring(orderInfoVo.getCreateTime(), 0, 19));
					} else {
						zeroPayInfo.setPay_time(StringUtils.substring(orderInfoVo.getPayTime(), 0, 19));
					}
					zeroPayInfo.setPay_no(payId);
					zeroPayInfo.setPay_number(t_id);
					payInfoList.add(zeroPayInfo);
				}

				//推送oms
				String data = JSON.toJSONString(orderForXZOMSVo);
				data = Base64.encodeBytes(data.getBytes("utf-8"));
				String sign = MD5.passmd5(data + Config.getString("xz.secret"));
				PublicForXZOMSVo publicForXZOMSVo = new PublicForXZOMSVo();
				publicForXZOMSVo.setMethod("trade.add");
				publicForXZOMSVo.setTimestamp(ExtendMethod.getCurrentDateTime());
				publicForXZOMSVo.setSign(sign);
				publicForXZOMSVo.setApp_key(Config.getString("xz.appKey"));
				publicForXZOMSVo.setData(data);
				String publicJson = JSON.toJSONString(publicForXZOMSVo);
				result = HttpUtil.doPost(publicJson, Config.getString("xz.sendOrder"), "application/json; charset=UTF-8");
				JSONObject requestJson = JSONObject.parseObject(result);
				xzOmsLogService.deleteByPrimaryOrderSn(orderObjectOrderSn, orderInfoSn);
				if (!requestJson.getString("code").equals("00000") && !requestJson.getString("code").equals("01000")) {
					XzOmsLog xzOmsLog = new XzOmsLog();
					xzOmsLog.setOrderSn(orderObjectOrderSn);
					xzOmsLog.setOrderInfoSn(orderInfoSn);
					if (result == null || result.isEmpty()) {
						result = "系统内数据异常，联系人工排查处理";
					}
					xzOmsLog.setResult(result);
					xzOmsLogService.insertSelective(xzOmsLog);
					isReturn = false;
					pushOmsSuccess = false;
				} else {
					isReturn = false;
				}
			}
			if (isReturn && giftNum > 0) {
				throw new PlatformException("推送订单失败: orderObjectOrderSn :" + orderObjectOrderSn + " --------添加赠品失败, 原因是 giftNum > 0 isReturn = TRUE ");
			}
			if (pushOmsSuccess) {
				try {
					orderDao.updateHandlestatusByOrderSn(orderObjectOrderSn);
				} catch (Exception e) {
					logger.error("订单[{}]推送oms成功，但更新推送成功标识失败:{} ", orderObjectOrderSn, e.getMessage(), e);
				}
			}
		} catch (PlatformException e) {
			logger.error("订单[{}]推送oms异常:{}", orderObjectOrderSn, e.getMessage(), e);
			throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
		} catch (Exception e) {
			logger.error("订单[{}]推送oms异常:{}", orderObjectOrderSn, e.getMessage(), e);
			throw new PlatformException(ErrorEnum.C20000, ErrorEnum.C20000.getMessage());
		}
	}

	@Override
	protected CompanyXzVo setCompany(ResponseUser user, TalentJob talentJob, CompanyXzVo companyXz, List<OrderDetail> inOrderDetailList) throws Exception {
		String recommendFrom = null;// 身份id
		if (inOrderDetailList.get(0).getTalentId() != null && inOrderDetailList.get(0).getTalentId().longValue() > 0) {// 达人分享商品，如果分享人是讲师取此达人的推荐人身份id，如果不是讲师达人取此达人的分享达人身份id
			ResponseUser recommendFromUser = userService.selectUserRoleById(inOrderDetailList.get(0).getTalentId());
			if (recommendFromUser.getLevel() == CommonConstants.TALENT_TEACHER_LEVEL) {
				recommendFrom = recommendFromUser.getRecommendFrom();
			} else if (recommendFromUser.getLevel() >= CommonConstants.TALENT_MIN_LEVEL && recommendFromUser.getLevel() <= CommonConstants.TALENT_MAX_LEVEL) {
				recommendFrom = recommendFromUser.getTalentTeacher();
			}
		} else {// 不是达人分享商品，取购买人推荐人身份id，如果此人的普通推荐人不是达人讲师取此人普通推荐人的达人导师身份id
			recommendFrom = user.getRecommendFrom();
			ResponseUser recommendFromUser = userService.selectUserRoleByPersonId(recommendFrom);
			if (recommendFromUser != null && recommendFromUser.getLevel() != CommonConstants.TALENT_TEACHER_LEVEL) {
				recommendFrom = recommendFromUser.getTalentTeacher();
			}
		}
		if (recommendFrom == null || recommendFrom.isEmpty()) {
			// TODO 无讲师 默认为公共讲师(GZ106163)
			recommendFrom = BaseConstants.XZ_SISTER_PERSION_ID;
		}
		// 获取讲师
		try {
			talentJob = talentJobSerice.selectTalentJobByPersonId(recommendFrom);
		} catch (TooManyResultsException e) {
			logger.error("根据讲师身份[{}]找到多条讲师信息", recommendFrom);
			throw new PlatformException(ErrorEnum.C20107, "一个讲师对应多条讲师信息");
		}
		if (talentJob == null) {// 推荐人不是讲师 默认为公共讲师(GZ106163)
			talentJob = talentJobSerice.selectTalentJobByPersonId(BaseConstants.XZ_SISTER_PERSION_ID);
		}
		String result = HttpUtil.doPost("userName=" + talentJob.getJobNo(), Config.getString("xz.getUser"), null);
		OrderForThirdResponseXzResult<OrderForXZTeacherVo> orderForThirdResponseXzResult = new OrderForThirdResponseXzResult<OrderForXZTeacherVo>(new OrderForXZTeacherVo());
		orderForThirdResponseXzResult = JSON.parseObject(result, new TypeReference<OrderForThirdResponseXzResult<OrderForXZTeacherVo>>() {});
		String branchId = null;
		if (orderForThirdResponseXzResult.getResult()) {
			branchId = orderForThirdResponseXzResult.getData().getBranchId();
		} else {
			logger.error("talentJob.getJobNo()=" + talentJob.getJobNo());
			throw new PlatformException(ErrorEnum.C20700, ErrorEnum.C20700.getMessage());
		}
		companyXz = companyService.selectByBranchId(branchId);
		if (companyXz == null) {
			logger.error("讲师[{}]所属分公司[{}]为空", talentJob.getJobNo(), branchId);
			throw new PlatformException(ErrorEnum.C20700, ErrorEnum.C20700.getMessage());
		} else {
			companyXz.setJobNo(talentJob.getJobNo());
		}
		// }
		return companyXz;
	}

	@Override
	protected OrderSettlement createOrderSettlement(
			Map<Long, OrderInfo> orderInfoIdMap, OrderDetail orderDetail,
			Map<Long, InventoryVo> inventoryMap, CompanyXz companyXz,
			boolean isSub, int currSettlementPriceDealer, int currCashCoinDealer,int currBalancePaidDealer) {
		OrderSettlement orderSettlement = createOrderSettlement(orderInfoIdMap,
				orderDetail, inventoryMap);
		orderSettlement.setGoodsType(orderDetail.getGoodsType());
		orderSettlement.setSelfSupport(inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport());

		orderSettlement.setSettlementRateDealer(inventoryMap.get(orderDetail.getInventoryId()).getSettlementRateDealer());
		orderSettlement.setSettlementRateManager(inventoryMap.get(orderDetail.getInventoryId()).getSettlementRateManager());

		orderSettlement.setSettlementPriceDealer((int) (Math.round((double) orderDetail.getTotalFee() * orderSettlement.getSettlementRateDealer() / 100)));
		orderSettlement.setCashCoinDealer((int) (Math.round((double) orderDetail.getCashCoin() * orderSettlement.getSettlementRateDealer() / 100)));
		orderSettlement.setBalancePaidDealer((int) (Math.round((double) orderDetail.getBalancePaid() * orderSettlement.getSettlementRateDealer() / 100)));

		orderSettlement.setSettlementPriceManager(orderDetail.getTotalFee() - orderSettlement.getSettlementPriceDealer());
		orderSettlement.setCashCoinManager(orderDetail.getCashCoin() - orderSettlement.getCashCoinDealer());
		orderSettlement.setBalancePaidManager(orderDetail.getBalancePaid() - orderSettlement.getBalancePaidDealer());
		
		return orderSettlement;
	}
	
	/***
	 * 
	 * @param settlementId
	 * @throws Exception
	 */
	public void divideSettlementRow(Long settlementId) throws RuntimeException{
		    OrderSettlement orderSettlement = orderSettlementMapper.selectByPrimaryKey(settlementId);
		    if(orderSettlement != null && orderSettlement.getStatus() == 1) {
		    	//
		    	//开始获取支付信息
		    	List<OrderPay> list = orderPayMapper.selectOrderPayInfoById(settlementId);
		    	if(CollectionUtils.isEmpty(list)) {
		    		throw new PayException(settlementId + "  该行结算ID找不到对应的支付信息,请人工确认处理后进行清分!");
		    	}
		    	if(list.size() > 1) {
		    		throw new PayException(settlementId + "  该行结算ID对应一条以上的成功支付信息,无法完成清分,请人工确认处理后进行清分!");
		    	}
		    	OrderPay orderPay = list.get(0);
		    	//开始获取公司清分账号
		    	Map<String,Object> orderUserInfoMap = orderSettlementMapper.selectOrderUserInfoById(settlementId);
		    	if(orderUserInfoMap == null) {
		    		throw new LedgerAccounException(settlementId + "  该行结算ID对应的订单信息异常,缺少对应的子订单信息，或者订单行信息!");
		    	}
		    	Object orderTalnetId = orderUserInfoMap.get("talent_id") == null ? "0" : orderUserInfoMap.get("talent_id");
		    	String recommendFrom = null;// 身份id
		    	if(orderTalnetId == null || Long.valueOf(orderTalnetId.toString()) == 0) {//非分享订单,所以取下单人的推荐人身份ID
		    		recommendFrom = (String)orderUserInfoMap.get("user_id_recommend_from");
					if(!StringUtils.isBlank(recommendFrom)) {
						ResponseUser recommendFromUser = userService.selectUserRoleByPersonId(recommendFrom);
						if (recommendFromUser != null	&& recommendFromUser.getLevel() != CommonConstants.TALENT_TEACHER_LEVEL) 
						{
							recommendFrom = recommendFromUser.getTalentTeacher();
						}
					}
		    	}else {//分享产品, 
		    		ResponseUser recommendFromUser = userService.selectUserRoleById(Long.valueOf(orderTalnetId.toString()));
					if (recommendFromUser.getLevel() == CommonConstants.TALENT_TEACHER_LEVEL) {
						recommendFrom = recommendFromUser.getRecommendFrom();
					} else if (recommendFromUser.getLevel() >= CommonConstants.TALENT_MIN_LEVEL && recommendFromUser.getLevel() <= CommonConstants.TALENT_MAX_LEVEL) {
						recommendFrom = recommendFromUser.getTalentTeacher();
					}
		    	}
		    	if (recommendFrom == null || recommendFrom.isEmpty()) {
					// TODO 无讲师 默认为公共讲师(GZ106163)
				recommendFrom = BaseConstants.XZ_SISTER_PERSION_ID;
				}
				// 获取讲师
		    	TalentJob talentJob = null;
				try {
					talentJob = talentJobSerice.selectTalentJobByPersonId(recommendFrom);
				} catch (TooManyResultsException e) {
					logger.error("根据讲师身份[{}]找到多条讲师信息", recommendFrom);
					throw new LedgerAccounException(recommendFrom +  "一个讲师对应多条讲师信息");
				}
				if (talentJob == null) {// 推荐人不是讲师 默认为公共讲师(GZ106163)
				talentJob = talentJobSerice.selectTalentJobByPersonId(BaseConstants.XZ_SISTER_PERSION_ID);
				}
				String result = null;
				try {
					result = HttpUtil.doPost("userName=" + talentJob.getJobNo(), Config.getString("xz.getUser"), null);
				}catch(IOException e) {
					throw new LedgerAccounException(talentJob.getJobNo() +  "  清分获取讲师所属公司出现错误:" + e.getMessage());
				}
				OrderForThirdResponseXzResult<OrderForXZTeacherVo> orderForThirdResponseXzResult = new OrderForThirdResponseXzResult<OrderForXZTeacherVo>(new OrderForXZTeacherVo());
				orderForThirdResponseXzResult = JSON.parseObject(result, new TypeReference<OrderForThirdResponseXzResult<OrderForXZTeacherVo>>() {});
				String branchId = null;
				if (orderForThirdResponseXzResult.getResult()) {
					branchId = orderForThirdResponseXzResult.getData().getBranchId();
				} else {
					logger.error("talentJob.getJobNo()=" + talentJob.getJobNo());
					throw new LedgerAccounException(talentJob.getJobNo() + "从讲师APP后台实时获取讲师分公司错误 "  );
				}
				CompanyXzVo companyXz = companyService.selectByBranchId(branchId);
				if (companyXz == null) {
					logger.error("讲师[{}]所属分公司[{}]为空", talentJob.getJobNo(), branchId);
					throw new LedgerAccounException(talentJob.getJobNo() + "对应的分公司为空 branchId =" + branchId);
				} else {
					companyXz.setJobNo(talentJob.getJobNo());
				}
		    	String settlementNo = OrderUtil.getOrderSn();
				YeePayDivideModel model = new YeePayDivideModel();
				model.setRequestid(settlementNo);
				model.setOrderrequestid(orderPay.getPaySn());
				if (orderSettlement.getSelfSupport().intValue() == GoodsSelfTypeEnum.T1.getCode()) {
					orderSettlement.setCompanyAccount(Config.getString("xz.yeepay.yzAccount"));
				} else {
					if (companyXz != null) {
						orderSettlement.setCompanyAccount(companyXz
								.getCompanyAccount());
						orderSettlement.setManagerAccount(companyXz
								.getManagerAccount());
					}
				}
			
				model.setDivideinfo(orderSettlement.getCompanyAccount()
						+ ":AMOUNT"
						+ (((double) orderSettlement.getSettlementPriceDealer()) / 100)
						+ (orderSettlement.getManagerAccount() != null
								&& !orderSettlement.getManagerAccount().isEmpty() ? ("|"
								+ orderSettlement.getManagerAccount() + ":AMOUNT" + (((double) orderSettlement
								.getSettlementPriceManager()) / 100)) : ""));
				String settlementResult = yeePay.yeePayDivide(model);
				JSONObject json = null;
				try {
					json = JSONObject.parseObject(settlementResult);
				}catch (Exception e) {
					throw new LedgerAccounException( "调用易宝出现返回值异常" + settlementResult);
				}
				
				String settlementCode = json.getString("code");
				if (settlementCode.equals("1")) {
					int uResult = updateStatusBySettlementId(settlementId,
							SettlementStatusEnum.S2.getCode(), settlementNo,
							orderSettlement.getCompanyAccount(),
							orderSettlement.getManagerAccount());
				} else {
					throw new LedgerAccounException( "调用易宝出现返回值异常" + settlementResult);
				}
		    }
	}

	public void divideByParentOrderSn(String orderSn) {
		List<OrderSettlement> settlementList = orderSettlementMapper.selectSettlementByOrderSn(orderSn);
		for(OrderSettlement ol : settlementList) {
			try {
				divideSettlementRow(ol.getId());
			}catch(Exception e) {
				logger.error("清分错误, 结算行ID ： {} 错误信息: "  , ol.getId(), e.getMessage(),e);
				String errorMsg = e.getMessage() == null ? "" : e.getMessage();
				errorMsg = errorMsg.length() > 200 ? errorMsg.substring(0, 200) : errorMsg;
				OperationLog log = new OperationLog();
				log.setDescription(errorMsg);
				log.setModule("SETTLEMENT_QF");
				log.setOperateType("SETTLEMENT_QF");
				log.setObjId(Integer.parseInt(String.valueOf(ol.getId())));
				log.setObjName(String.valueOf(ol.getOrderSn()));
				operationLogMapper.insert(log);
			}
		}
	}
	/**
	 * <dl>
	 * <dt>根据父订单号进行分账(只分账易宝支付的单子{Type 20,21,22,23,24})</dt>
	 * </dl>
	 * @param orderSn
	 * @author gaoweiqi
	 * @date 2017年8月29日 12:44:05
	 */
	@Override
	public void divide(String orderSn) throws Exception {
		OrderObject orderObj= orderObjectMapper.selectByOrderSn(orderSn);
		OrderDetail OpenStoreOrderDetail=null;
		int OpenStoreGoodsNumber=0;
		 Map<Object,Object> baseRestrictionsMap=null;
        //订单属于易宝的订单
		List<OrderPay> list=orderPayMapper.selectPaySuccessByOBJOrderSn(orderSn);
		int [] YeePayType={20,21,22,23,24};//易宝支付
		if(list==null||list.size()==0||!ArrayUtils.contains(YeePayType,list.get(0).getPayType())){//易宝支付
			return;
		}
		if(orderObj.getOpenStore()==1){//是开店单 去查找开店商品
			BaseRestrictions openStoreRestrictions=null;
			List<OrderDetail> OrderDetailList=
					orderDetailMapper.selectOrderDetilByOrderObjectId(orderObj.getId());
            for(OrderDetail OrderDetail:OrderDetailList){
            	if(OrderDetail.getIsOpenStoreGoods()==1){//开店商品
            		OpenStoreOrderDetail=OrderDetail;
            		OpenStoreGoodsNumber+=OrderDetail.getQuantity();
            	}
            }
            if(OpenStoreGoodsNumber!=1){//开店商品数量不对
            	logger.error("-------------->开店单开店数量异常:订单号:{} 开店商品数量:{}",orderSn,OpenStoreGoodsNumber);
            	throw new Exception("开店单开店数量异常");
            }
            //通过配置表获取开店商品的分账信息 如果没有就暂时不分账  open_store_settlement_2422
            openStoreRestrictions=
					baseRestrictionsService.getBaseRestrictionsForCache("open_store_settlement_" + OpenStoreOrderDetail.getGoodId());
            if(openStoreRestrictions==null||openStoreRestrictions.getExperience()==0
            		||StringUtils.isBlank(openStoreRestrictions.getName())){
				logger.error("开店分账信息未配置{}", "open_store_settlement_" + OpenStoreOrderDetail.getGoodId());
            	throw new Exception("开店分账信息未配置");
            }
            if(openStoreRestrictions.getExperience()!=OpenStoreOrderDetail.getTotalFee()){
            	logger.error("开店商品金额和实付金额不一致 订单明细id:{} 实付:{} 配置:{}",
            			OpenStoreOrderDetail.getId(),OpenStoreOrderDetail.getTotalFee(),openStoreRestrictions.getExperience());
            	throw new Exception("开店商品金额和实付金额不一致");
            }
          baseRestrictionsMap=JSONObject.parseObject(openStoreRestrictions.getName(),Map.class);
		}

		
		OrderPay orderPay=list.get(0);
		List<OrderSettlement> orderSettlementList = orderSettlementMapper.selectSettlementByOrderSn(orderSn);
		if(orderSettlementList==null||orderSettlementList.size()==0)
			return;
		
		for (OrderSettlement orderSettlement : orderSettlementList) {
			if(OpenStoreOrderDetail!=null&&
			orderSettlement.getOrderDetailId()==OpenStoreOrderDetail.getId().longValue()){//当前结算单数据开店单的开单商品
				String settlementNo = OrderUtil.getOrderSn();
				orderSettlement.setCompanyAccount(baseRestrictionsMap.get("companyAccount").toString());
				orderSettlement.setManagerAccount(baseRestrictionsMap.get("managerAccount").toString());
				orderSettlement.setSettlementPriceDealer(Integer.parseInt(baseRestrictionsMap.get("settlementPriceDealer").toString()));
				orderSettlement.setSettlementPriceManager(Integer.parseInt(baseRestrictionsMap.get("settlementPriceManager").toString()));
				orderSettlement.setCashCoinDealer(0);
				orderSettlement.setCashCoinManager(0);
				orderSettlement.setBalancePaidDealer(0);
				orderSettlement.setBalancePaidManager(0);
				orderSettlement.setSettlementRateDealer(Integer.parseInt(baseRestrictionsMap.get("settlementRateDealer").toString()));
				orderSettlement.setSettlementRateManager(Integer.parseInt(baseRestrictionsMap.get("settlementRateManager").toString()));

				YeePayDivideModel model = new YeePayDivideModel();
				model.setRequestid(settlementNo);
				model.setOrderrequestid(orderPay.getPaySn());
				model.setDivideinfo(orderSettlement.getCompanyAccount()
						+ ":AMOUNT"
						+ (((double) orderSettlement.getSettlementPriceDealer()) / 100)
						+ ("|"+ orderSettlement.getManagerAccount() + ":AMOUNT" + (((double) orderSettlement
								.getSettlementPriceManager()) / 100)));
				String settlementResult = yeePay.yeePayDivide(model);
				JSONObject json = JSONObject.parseObject(settlementResult);
				String settlementCode = json.getString("code");
				if (settlementCode.equals("1")) {
					orderSettlementMapper.updateByPrimaryKey2(orderSettlement.getId(),
							SettlementStatusEnum.S2.getCode(), settlementNo,
							orderSettlement);
				}
			}else{
				//设置分账公司
				CompanyXzVo companyXz = null;
				List<OrderInfoVo> OrderInfoVoList=
						orderInfoMapper.selectOrderInfoVoByStatusOrderObjectSn(orderSn, 2);
				if(OrderInfoVoList!=null&&OrderInfoVoList.size()>0&&StringUtils.isNotBlank(OrderInfoVoList.get(0).getJobNo())){
					int CompanyId=OrderInfoVoList.get(0).getCompanyId();
					String JobNo=OrderInfoVoList.get(0).getJobNo();
					 companyXz=companyService.selectBycompany_Id(CompanyId);
					 companyXz.setJobNo(JobNo);
				}
				if(companyXz==null){
					return;
				}
				//设置运费的分账公司
				if (orderSettlement.getSelfSupport().intValue() == GoodsSelfTypeEnum.T1.getCode()) {
					orderSettlement.setCompanyAccount(Config.getString("xz.yeepay.yzAccount"));
				} else {
					//需要两个公司进行分账
					if(StringUtils.isBlank(companyXz.getCompanyAccount())||StringUtils.isBlank(companyXz.getManagerAccount())){
						return;
					}
						orderSettlement.setCompanyAccount(companyXz.getCompanyAccount());
						orderSettlement.setManagerAccount(companyXz.getManagerAccount());
				}
				String settlementNo = OrderUtil.getOrderSn();
				YeePayDivideModel model = new YeePayDivideModel();
				//实际支付为0 不需要分账 直接设置结算单为已分账
				if(orderSettlement.getTotalFee()==0){
					int uResult = updateSettlementStatusByID(orderSettlement.getId(),
							SettlementStatusEnum.S2.getCode(), settlementNo,
							orderSettlement.getCompanyAccount(),
							orderSettlement.getManagerAccount(),
							orderSettlement.getSelfSupport());
					if (uResult <= 0) {
						logger.error(ErrorEnum.C21199.getMessage() + orderSn);
					}
					continue;
				}
				model.setRequestid(settlementNo);
				model.setOrderrequestid(orderPay.getPaySn());
				model.setDivideinfo(orderSettlement.getCompanyAccount()
						+ ":AMOUNT"
						+ (((double) orderSettlement.getSettlementPriceDealer()) / 100)
						+ (orderSettlement.getManagerAccount() != null
								&& !orderSettlement.getManagerAccount().isEmpty() ? ("|"
								+ orderSettlement.getManagerAccount() + ":AMOUNT" + (((double) orderSettlement
								.getSettlementPriceManager()) / 100)) : ""));
				String settlementResult = yeePay.yeePayDivide(model);
				JSONObject json = JSONObject.parseObject(settlementResult);
				String settlementCode = json.getString("code");
				if (settlementCode.equals("1")) {
					         updateSettlementStatusByID(orderSettlement.getId(),
							SettlementStatusEnum.S2.getCode(), settlementNo,
							orderSettlement.getCompanyAccount(),
							orderSettlement.getManagerAccount(),
							orderSettlement.getSelfSupport());
				}
		}
		}
		
	}

	/** b区商品，只支持易宝支付，其它使用除易宝以外所有支付方式 */
	@Override
	protected void setPayTypeConfig(
			ResponseGetOrderObject responseGetOrderObject) {
		// 当前可用支付类型
		List<PayTypeConfig> payTypeConfigList = new ArrayList<PayTypeConfig>();
		// 查询当前可用支付类型
		List<PayTypeConfig> payTypeConfigList0 = selectPayTypeConfigByStatus(StatusEnum.S1
				.getCode());
		for (PayTypeConfig payTypeConfig : payTypeConfigList0) {
			if (responseGetOrderObject.getGoodsSimpleVoList().get(0)
					.getGoodsType() == GoodsTypeEnum.T1.getCode()) {// b区商品，只支持易宝支付
				if (payTypeConfig.getPayType().intValue() >= PayTypeEnum.T20
						.getCode().intValue()
						&& payTypeConfig.getPayType().intValue() <= PayTypeEnum.T24
								.getCode().intValue()) {
					payTypeConfigList.add(payTypeConfig);
				}
			} else {// b区以外商品用除易宝以外支付方式
				if (payTypeConfig.getPayType().intValue() < PayTypeEnum.T20
						.getCode().intValue()
						|| payTypeConfig.getPayType().intValue() > PayTypeEnum.T24
								.getCode().intValue()) {
					payTypeConfigList.add(payTypeConfig);
				}
			}
		}
		responseGetOrderObject.setPayTypeConfigList(payTypeConfigList);
	}

	@Override
	public int updateOrderObjectPayUrlById(long id, String payUrl) {
		return orderDao.updateOrderObjectPayUrlById(id, payUrl);
	}

	/**
	 * 获取退款分账信息
	 */
	@Override
	public String selectDivideString(Long orderDetailId) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		OrderSettlement settlement = orderSettlementMapper
				.selectByOrderDetailId(orderDetailId);
		if (settlement == null) {
			return "";
		}

		if (settlement.getStatus() != 2) {
			return "FAIL";
		}

		if (settlement.getCompanyAccount() != null
				&& !"".equals(settlement.getCompanyAccount())) {
			sb.append(settlement.getCompanyAccount());
			sb.append(":AMOUNT");
			sb.append(settlement.getSettlementPriceDealer().doubleValue() / 100);
			if (settlement.getManagerAccount() != null
					&& !"".equals(settlement.getManagerAccount())) {
				sb.append("|");
				sb.append(settlement.getManagerAccount());
				sb.append(":AMOUNT");
				sb.append(settlement.getSettlementPriceManager().doubleValue() / 100);
			}
		}
		return sb.toString();
	}
	
	/**
	 * 获取运费退款分账信息
	 * gaoweiqi
	 * 2017-09-14 10:50
	 */
	@Override
	public String selectFreightDivideString(OrderSettlement settlement) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
//		OrderSettlement settlement = orderSettlementMapper
//				.selectByOrderDetailId(orderinfoID);
		if (settlement == null||settlement.getStatus() != 2) {
			return "FAIL";
		}

		if (settlement.getCompanyAccount() != null
				&& !"".equals(settlement.getCompanyAccount())) {
			sb.append(settlement.getCompanyAccount());
			sb.append(":AMOUNT");
			sb.append(settlement.getSettlementPriceDealer().doubleValue() / 100);
			if (settlement.getManagerAccount() != null
					&& !"".equals(settlement.getManagerAccount())) {
				sb.append("|");
				sb.append(settlement.getManagerAccount());
				sb.append(":AMOUNT");
				sb.append(settlement.getSettlementPriceManager().doubleValue() / 100);
			}
		}
		return sb.toString();
	}

	@Override
	public void updateOrderObjectFreightNo(Long orderObjectId,
			String refundFeeNo) {
		// TODO Auto-generated method stub
		orderDao.updateOrderObjectFreightNo(orderObjectId, refundFeeNo);
	}

	@Override
	public int selectDetailGoodsType(Long orderObjectId) {
		// TODO Auto-generated method stub
		return orderDao.selectDetailGoodsType(orderObjectId);
	}

	@Override
	public String selectSettlementAccount(Long orderObjectId) {
		// TODO Auto-generated method stub
		return orderDao.selectSettlementAccount(orderObjectId);
	}

	@Override
	public List<OrderObject> selectDiTemp() {
		// TODO Auto-generated method stub
		return null;
	}
	/**
	 * <dl>
	 * <dt>查询可分账订单</dt>
	 * </dl>
	 * @return List String(可分账的父订单的订单号){仅处理易宝的订单}
	 * @author gaoweiqi
	 * @date 2017年8月29日 12:44:05
	 */
	@Override
	public List<String> selectOrderClearing() {
		// TODO Auto-generated method stub
		List<String> listOrderSn = orderSettlementMapper.selectOrderOrderSettlementByStatus();
		List<Long> orderObjectIdList = orderInfoMapper.selectOrderByOrderSnList(listOrderSn);
		List<String> orderList = orderObjectMapper.selectOrderObjectByIdListWithStatusAndPayType(orderObjectIdList,new int[]{20,21,22,23,24},new int[]{2,3,4,6});
		return orderList;
	}

	/** 计算开店销总售价：金额大于设置开店销售总价，对销售总价进行优惠 （销售总价-b区自主商品销售总价*（1-优惠比例）） */
	@Override
	protected OpenStorePriceVo compOpenStorePrice(ResponseUser user,
			int openStoreSelfFee, int totalPrice) {
		OpenStorePriceVo openStorePriceVo = new OpenStorePriceVo();
		Map<String, BaseRestrictions> baseRestrictionsMap = selectAllBaseRestrictions();
		if (openStoreSelfFee >= baseRestrictionsMap.get(
				BaseRestrictionsEnum.T6.getText()).getRestrictions()) {
			totalPrice = totalPrice
					- openStoreSelfFee
					+ openStoreSelfFee
					* baseRestrictionsMap
							.get(BaseRestrictionsEnum.T6.getText())
							.getExperience() / 100;
			openStorePriceVo.setTotalPrice(totalPrice);
			openStorePriceVo.setExperience(baseRestrictionsMap.get(
					BaseRestrictionsEnum.T6.getText()).getExperience());
		} else {
			openStorePriceVo.setTotalPrice(totalPrice);
		}
		return openStorePriceVo;
	}

	/** 满足开店订单按开店优惠计算销售价：商品是B区且为自营计算优惠 */
	@Override
	protected void compOpenStoreODPrice(int oldTotalPrice, int totalPrice,
			OpenStorePriceVo openStorePriceVo,
			List<GoodsSimpleVo> goodsSimpleVoList) {
		if (oldTotalPrice != totalPrice) {
			for (GoodsSimpleVo goodsSimpleVo : goodsSimpleVoList) {
				if (goodsSimpleVo.getGoodsType() == GoodsTypeEnum.T1.getCode()
						&& goodsSimpleVo.getSelfSupport() == GoodsSelfTypeEnum.T0
								.getCode()) {
					goodsSimpleVo.setSalePrice(goodsSimpleVo.getSalePrice()
							* openStorePriceVo.getExperience() / 100);
				} else {
					goodsSimpleVo.setSalePrice(goodsSimpleVo.getSalePrice());
				}
			}
		}
	}

	/** 返回开店优惠折扣，如果满足开店订单，标记订单为开店订单 */
	@Override
	protected int compOpenStorePrice(
			Map<String, BaseRestrictions> baseRestrictionsMap,
			int openStoreSelfFee, OrderObject orderObject) {
		int experience = baseRestrictionsMap.get(
				BaseRestrictionsEnum.T6.getText()).getExperience();
		if (openStoreSelfFee >= baseRestrictionsMap.get(
				BaseRestrictionsEnum.T6.getText()).getRestrictions()) {
			// orderObject.setTotalPrice(orderObject.getTotalPrice()-openStoreSelfFee+openStoreSelfFee*
			// baseRestrictionsMap.get(BaseRestrictionsEnum.T6.getText()).getExperience()/100);
			orderObject.setOpenStore(1);
		}
		return experience;
	}

	@Override
	protected void compOpenStoreInfoPrice(int experience,
			Map<Integer, Integer> openStoreSelfFeeMap, int openStoreSelfFee,
			OrderObject orderObject, OrderInfo orderInfo) {
		if (openStoreSelfFeeMap.get(orderInfo.getStoreId()) != null) {
			if (orderObject.getOpenStore() != null
					&& orderObject.getOpenStore().intValue() == 1) {
				orderInfo.setTotalPrice(orderInfo.getTotalPrice() * experience
						/ 100);
			}
		}
	}

	@Override
	protected void compOpenStoreDetailPrice(int experience,
			OrderObject orderObject, OrderDetail orderDetail,
			Map<Long, InventoryVo> inventoryMap) {
		// FIXME
		// 是开店单且商品为自营商品(与去交易单时判断不一致，缺少判断商品是否属于b区，目前b、c区不能同时支付，不会出现C区自营商品进行开店首单优惠情况)
		if (orderObject.getOpenStore() != null
				&& orderObject.getOpenStore().intValue() == 1
				&& inventoryMap.get(orderDetail.getInventoryId())
						.getSelfSupport() == GoodsSelfTypeEnum.T0.getCode()) {
			inventoryMap.get(orderDetail.getInventoryId()).setSalePrice(
					inventoryMap.get(orderDetail.getInventoryId())
							.getSalePrice() * experience / 100);
		}
	}

	@Override
	protected OpenStoreTypeEnum checkOpenStoreCommision(ResponseUser user, OrderObject orderObject, Map<String, ResponseUser> shareRecommendUserMap, Map<Long, ResponseUser> talentIdAndUserReMap, long talentId) {
		// 首单且（存在普通推荐人身份或会员推荐人身份）
		if ((orderObject.getOpenStore() != null && orderObject.getOpenStore() == 1) && (shareRecommendUserMap.get(user.getRecommendFrom()) != null || talentIdAndUserReMap.get(talentId) != null)) {
			if (talentId == 0) {// 不是达人分享
				if (shareRecommendUserMap.get(user.getRecommendFrom()).getLevel() == CommonConstants.TALENT_TEACHER_LEVEL) {// 当前用户为讲师级别，讲师店
					return OpenStoreTypeEnum.T2;
				} else {// 学生店
					return OpenStoreTypeEnum.T2;
				}
			} else {// 达人商品
				if (talentIdAndUserReMap.get(talentId).getLevel() == CommonConstants.TALENT_TEACHER_LEVEL) {// 达人为讲师级别
					return OpenStoreTypeEnum.T2;
				} else {// 学生店
					return OpenStoreTypeEnum.T2;
				}
			}
		} else {
			return OpenStoreTypeEnum.T0;
		}
	}

	@Override
	protected int openStoreCommision(OpenStoreTypeEnum openStoreTypeEnum,
			int commisionPrice,
			Map<String, BaseRestrictions> baseRestrictionsMap, int fee,
			Map<Long, InventoryVo> inventoryMap, OrderDetail orderDetail) {
		// 商品是自营且店铺类型是学生店，计算分佣比例
		if (inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport() == GoodsSelfTypeEnum.T0
				.getCode()
				&& openStoreTypeEnum.getCode() == OpenStoreTypeEnum.T2
						.getCode()) {
			fee = commisionPrice
					* baseRestrictionsMap
							.get(BaseRestrictionsEnum.T7.getText())
							.getExperience();
		}
		return fee;
	}

	@Override
	protected String openStoreComment(OpenStoreTypeEnum openStoreTypeEnum,
			String comment, Map<Long, InventoryVo> inventoryMap,
			OrderDetail orderDetail) {
		// 商品是自营且开店店铺类型值大于0，标记为开店分佣
		if (inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport() == GoodsSelfTypeEnum.T0
				.getCode() && openStoreTypeEnum.getCode() > 0) {
			comment = CommonConstants.COMMISION_DESC_OPEN_STORE;
		}
		return comment;
	}

	@Override
	protected int openStoreCommision2(OpenStoreTypeEnum openStoreTypeEnum,
			int commisionPrice,
			Map<String, BaseRestrictions> baseRestrictionsMap, int fee,
			Map<Long, InventoryVo> inventoryMap, OrderDetail orderDetail) {
		// 自主商品且是学生店
		if (inventoryMap.get(orderDetail.getInventoryId()).getSelfSupport() == GoodsSelfTypeEnum.T0
				.getCode()
				&& openStoreTypeEnum.getCode() == OpenStoreTypeEnum.T2
						.getCode()) {
			fee = commisionPrice
					* baseRestrictionsMap
							.get(BaseRestrictionsEnum.T7.getText())
							.getRestrictions();
		}
		return fee;
	}

	@Override
	protected void setOpenStoreUser(RequestOrderDetail requestOrderDetail,
			ResponseUser user, OrderObject orderObject) {
		// 购买商品为B区&&(用户推荐人身份id不为空||购买商品达人id不为空)
		if (requestOrderDetail.getOrderDetailList().get(0).getGoodsType() == GoodsTypeEnum.T1
				.getCode()
				&& (user.getRecommendFrom() != null
						&& !user.getRecommendFrom().isEmpty() || requestOrderDetail
						.getOrderDetailList().get(0).getTalentId().longValue() > 0)) {
			// 以购买商品分享达人id为主，如果没有取当前用户推荐人
			if (requestOrderDetail.getOrderDetailList().get(0).getTalentId()
					.longValue() == 0) {
				UserInfo userInfo = userService.selectUserInfoByPersionId(user
						.getRecommendFrom());
				if (userInfo != null) {
					orderObject.setOpenStoreUserId(userInfo.getUserId());
				}
			} else {
				orderObject.setOpenStoreUserId(requestOrderDetail
						.getOrderDetailList().get(0).getTalentId());
			}
		}
	}

	/** 交易单为开店单，更新购买人身份id*/
	@Override
	protected void updateOpenStore(OrderObject orderObject) throws PlatformException {
		if (orderObject.getOpenStore() != null && orderObject.getOpenStore().intValue() > 0) {// 开店单
			Map<String,Object> params = new HashMap<String, Object>();
			params.put("orderSn",orderObject.getOrderSn());
			int sendCount = 0;
			while (true){
			    if (sendCount<3){
                    try {
                        orderQueueService.openStoreDone(params);
						logger.error("开店成功投递消息成功，消息内容："+JSONObject.toJSONString(params)+"==========");
                        break;
                    }catch (Exception e){
                        logger.error("开店成功投递消息失败第"+sendCount+"次，消息内容："+JSONObject.toJSONString(params)+"=========="+e.toString());
                        sendCount++;
                    }
                }else{
			        redisUtil.sadd(RedisKey.REDIS_KEY_QUEUE_FAILE+"openStoreDone",JSONObject.toJSONString(params));
			        break;
                }
            }
		}
	}

	@Override
	public void OrderSettlementartificialEliminate(
			List<String> orderObjectSnlist) {
		// TODO Auto-generated method stub
		// YeePayDivideModel model = new YeePayDivideModel();
		// orderObjectMapper.selectByOrderSn(orderSn)
		// model.setRequestid(settlementNo);
		// model.setOrderrequestid(orderSn);
		// model.setDivideinfo(orderSettlement.getCompanyAccount() + ":AMOUNT"
		// + (((double) orderSettlement.getSettlementPriceDealer()) / 100)
		// + (orderSettlement.getManagerAccount() != null &&
		// !orderSettlement.getManagerAccount().isEmpty()
		// ? ("|" + orderSettlement.getManagerAccount() + ":AMOUNT"
		// + (((double) orderSettlement.getSettlementPriceManager()) / 100))
		// : ""));
		// String settlementResult = yeePay.yeePayDivide(model);
		// JSONObject json = JSONObject.parseObject(settlementResult);
		// String settlementCode = json.getString("code");
	}

	@Override
	public List<User> selectOrderRecommendFromUser(Long id) {
		return orderObjectMapper.selectOrderRecommendFromUser(id);
	}

	@Override
	public String compareDivide(List<OrderSettlementVo> listSettle,
			Map<String, Double> YeePayDivide) {
		String code="1";
		Map<String, Double> APPdivide=new HashMap<String, Double>();
		for(OrderSettlementVo Vo:listSettle){
			if(StringUtils.isNotBlank(Vo.getCompanyAccount())){
				if(APPdivide.containsKey(Vo.getCompanyAccount())){
					APPdivide.put(Vo.getCompanyAccount(),NumberUtil.add(APPdivide.get(Vo.getCompanyAccount()),Vo.getSettlementPriceDealer().doubleValue()/100));
				}else{
					APPdivide.put(Vo.getCompanyAccount(), Vo.getSettlementPriceDealer().doubleValue()/100);
				}
			}
			if(StringUtils.isNotBlank(Vo.getManagerAccount())){
				if(APPdivide.containsKey(Vo.getManagerAccount())){
					APPdivide.put(Vo.getManagerAccount(),NumberUtil.add(APPdivide.get(Vo.getManagerAccount()),Vo.getSettlementPriceManager().doubleValue()/100));
				}else{
					APPdivide.put(Vo.getManagerAccount(), Vo.getSettlementPriceManager().doubleValue()/100);
				}
			}
		}
		if(YeePayDivide.size()!=APPdivide.size()){
			logger.error("分账信息错误"+YeePayDivide+"|"+APPdivide);
			return "2";
		}
		for(String strCOMPANY:YeePayDivide.keySet()){
			if(APPdivide.get(strCOMPANY).compareTo(YeePayDivide.get(strCOMPANY))!=0){
				logger.error("分账信息错误 公司:"+strCOMPANY+"| 金额"+APPdivide.get(strCOMPANY)+", "+YeePayDivide.get(strCOMPANY));
				logger.error("分账信息错误"+YeePayDivide+"|"+APPdivide);
				code="2";
				break;
			}
		}
		return code;
	}
	/**
	 * <dl>
	 * <dt>订单验证</dt>
	 * </dl>
	 * @param orderObj
	 * @return Map<String, Object> key:订单号 value:验证结果 
	 * @author gwq
	 * @date 2017年11月07日 下午3:07:54
	 */
	@Override
	public Map<String, Object> validationOrderObj(OrderObject orderObj) throws Exception{
		Map<String, Object> ResultMap=new HashMap<String, Object>();
		//验证订单的定时任务或者消息队列是否完成
		OrderSettlementCommision orderSettlementCommision=
				orderSettlementCommisionMapper.selectByorderSn(orderObj.getOrderSn());
		if(orderSettlementCommision==null&&StringUtils.compare(orderObj.getCreateTime(),"2017-12-29 23:18:31")>0){
			ResultMap.put("1",orderObj.getOrderSn());
			ResultMap.put("2", "订单异常 未找到对应的定时任务或者是队列任务");
			return ResultMap; 
		}
		//定时任务 没有执行完
		if(orderSettlementCommision!=null&&orderSettlementCommision.getStatus()==3||orderSettlementCommision.getStatus()==5){
				ResultMap.put("1",orderObj.getOrderSn());
				ResultMap.put("2", "定时任务或者是消息队列任务未完成，提示信息:"+orderSettlementCommision.getErrorMsg());
				return ResultMap; 
		}
		List<OrderDetail> listorderDetail=
				orderDetailMapper.selectOrderDetilByOrderObjectId(orderObj.getId());
		Map<Long,OrderDetail> orderDetailMap=new HashMap<Long,OrderDetail>();
		for(OrderDetail orderDetail:listorderDetail){
			orderDetailMap.put(orderDetail.getId(), orderDetail);
		}
		List<OrderPay>  Paylist=orderPayMapper.selectPaySuccessByOBJOrderSn(orderObj.getOrderSn());
		List<OrderSettlementVo> listSettlement=
				orderSettlementMapper.selectByOrderSnForSettlementDetail(orderObj.getOrderSn());
//		1. 验证所有已支付的订单(2,3,4,6,7) 如果支付使用了现金 和余额 还有妆币 
//		验证易宝  和自身流水记录 (金额一致 并且 不能有重复支付)
		if(orderObj.getTotalFee()>0&&!ListUtils.isNotEmpty(Paylist)){
			ResultMap.put("1",orderObj.getOrderSn());
			ResultMap.put("2", "非零元付订单未找到成功支付信息");
			return ResultMap; 
		}
		if(orderObj.getTotalFee()>0&&ListUtils.isNotEmpty(Paylist)&&Paylist.size()>1){
			ResultMap.put("1",orderObj.getOrderSn());
			ResultMap.put("2","该订单发现重复支付信息");
			return ResultMap; 
		}
		//验证实付金额 和分账信息(仅验证易宝支付的单子)
		if(orderObj.getTotalFee()>0&&orderObj.getPayType()>10){
			YeePayQueryDivideModel model=new YeePayQueryDivideModel();
			model.setOrderrequestid(Paylist.get(0).getPaySn());
			model.setCustomernumber(YeePay.CUSTOMER_NUMBER);
			String result=yeePay.yeePayQueryDivide(model);
			JSONObject JSONresult=JSONObject.parseObject(result);
			while(StringUtils.isBlank(JSONresult.getString("code"))){//查找分账信息失败 重新查找 
				logger.error("请求分账信息失败: {} 正在重新请求",Paylist.get(0).getPaySn());
				result=yeePay.yeePayQueryDivide(model);
			}
			JSONresult=JSONObject.parseObject(result);
			if("1".equals(JSONresult.getString("code"))){//查询分账信息成功
				Map<String, Double> divide=new HashMap<>();
				divide = yeePay.parsingYeePayDivide(JSONresult.getString("divideinfo"));
				double d=0.0;
				for(String str:divide.keySet()){
					d=NumberUtil.add(d,divide.get(str));
				}
				if(d!=(orderObj.getTotalFee().doubleValue()/100)){
					ResultMap.put("1",orderObj.getOrderSn());
					ResultMap.put("2", "查询订单分账信息和订单不符"+" 订单实付金额:"+(orderObj.getTotalFee().doubleValue()/100)+"  易宝分账金额:"+d);
					return ResultMap; 
				}
				String code=compareDivide(listSettlement,divide);
			    if("2".equals(code)){
			    	ResultMap.put("1",orderObj.getOrderSn());
					ResultMap.put("2", "查询订单分账信息和系统记录的分账信息不一致 "+"易宝分账:"+divide+"系统记录分账:"+JsonUtil.toJson(listSettlement));
					return ResultMap; 
			    }
			}else{
				ResultMap.put("1",orderObj.getOrderSn());
				ResultMap.put("2", "订单分账信息有误");
				return ResultMap;
			}
		}
		//用户使用了妆币支付
		if(orderObj.getCashCoin()>0){
			ParamsUserXzbTransactionVo params_user_xzb_transaction=new ParamsUserXzbTransactionVo();
			params_user_xzb_transaction.getBusinessTypeSet().add(14);//消费使用妆币
			params_user_xzb_transaction.setBusinessSourceId(orderObj.getId());
		  List<CUserPointTransaction> CUserPointTransactionList=
				 cUserPointTransactionService.queryAll(params_user_xzb_transaction);
		  if(!ListUtils.isNotEmpty(CUserPointTransactionList)){
			  ResultMap.put("1",orderObj.getOrderSn());
			  ResultMap.put("2", "未找到该订单对应的妆币支付事务");
			  return ResultMap;
		  }
		  if(ListUtils.isNotEmpty(CUserPointTransactionList)&&CUserPointTransactionList.size()>1){
			  ResultMap.put("1",orderObj.getOrderSn());
			  ResultMap.put("2", "该订单对应的妆币支付事务重复  重复次数"+CUserPointTransactionList.size()+" 事务明细"+JsonUtil.toJson(CUserPointTransactionList));
			  return ResultMap;
		  }
		  if((0-CUserPointTransactionList.get(0).getAmount().intValue())!=orderObj.getCashCoin().intValue()){
			  ResultMap.put("1",orderObj.getOrderSn());
			  ResultMap.put("2", "该订单对应的妆币支付事务和父订单妆币金额不一致");
			  return ResultMap;
		  }
		  if(CUserPointTransactionList.get(0).getTransactionStatus()!=1){
			  ResultMap.put("1",orderObj.getOrderSn());
			  ResultMap.put("2", "该订单对应的妆币支付事务状态异常");
			  return ResultMap;
		  }
		  //查找相对应的流水
		  List<UserPointJournal> userPointJournalList=
				 userPointJournalMapper.selectBySourceIDBusinessType(CUserPointTransactionList.get(0).getId(), 14);
		  if(!ListUtils.isNotEmpty(userPointJournalList)){
			  ResultMap.put("1",orderObj.getOrderSn());
			  ResultMap.put("2", "未找到该订单对应的妆币支付流水");
			  return ResultMap;
		  }
		  if(ListUtils.isNotEmpty(userPointJournalList)&&userPointJournalList.size()>1){
			  ResultMap.put("1",orderObj.getOrderSn());
			  ResultMap.put("2", "该订单对应的妆币支付流水重复");
			  return ResultMap;
		  }
		  if((0-userPointJournalList.get(0).getAmount().intValue())!=orderObj.getCashCoin().intValue()){
			  ResultMap.put("1", orderObj.getOrderSn());
			  ResultMap.put("2", "该订单对应的妆币支付流水和父订单金额不一致");
			  return ResultMap;
		  }
		}
		//用户使用了余额支付
		if(orderObj.getBalancePaid()>0){
			ParamsCommisionVo paramsCommisionVo = new ParamsCommisionVo();
			paramsCommisionVo.setStatus(1);
			paramsCommisionVo.setResult(1);
			paramsCommisionVo.setOrderObjectId(orderObj.getId());
			paramsCommisionVo.getBusinessTypeSet().add(5);//消费余额
			List<Commision> commisionList = commissionService.queryAll(paramsCommisionVo);
			 if(!ListUtils.isNotEmpty(commisionList)){
				 ResultMap.put("1",orderObj.getOrderSn());
				 ResultMap.put("2", "未找到该订单对应的余额支付事务");
				  return ResultMap; 
			  }
			  if(ListUtils.isNotEmpty(commisionList)&&commisionList.size()>1){
				  ResultMap.put("1",orderObj.getOrderSn());
				  ResultMap.put("2", "该订单对应的余额支付事务重复");
				  return ResultMap;
			  }
			  if((0-commisionList.get(0).getFee().intValue())!=orderObj.getBalancePaid().intValue()){
				  ResultMap.put("1", orderObj.getOrderSn());
				  ResultMap.put("2", "该订单对应的余额支付事务和父订单金额不一致");
				  return ResultMap;
			  }
			  if(commisionList.get(0).getResult()!=1||commisionList.get(0).getStatus()!=1){
				  ResultMap.put("1",orderObj.getOrderSn());
				  ResultMap.put("2", "订单对应的余额支付事务状态异常");
				  return ResultMap;
			  }
			  List<UserJournal> UserJournalList=
					  userJournalMapper.getUserJournalBySourceIDBusinessType(commisionList.get(0).getId(), 5);
			  if(!ListUtils.isNotEmpty(UserJournalList)){
				  ResultMap.put("1",orderObj.getOrderSn());
				  ResultMap.put("2", "未找到该订单对应的余额支付流水");
				  return ResultMap;
			  }
			  if(ListUtils.isNotEmpty(UserJournalList)&&UserJournalList.size()>1){
				  ResultMap.put("1",orderObj.getOrderSn());
				  ResultMap.put("2", "该订单对应的余额支付流水重复");
				  return ResultMap;
			  }
			  if((UserJournalList.get(0).getMoney())!=orderObj.getBalancePaid().intValue()){
				  ResultMap.put("1",orderObj.getOrderSn());
				  ResultMap.put("2", "该订单对应的余额支付流水和父订单金额不一致");
				  return ResultMap;
			  }
		}
		
		/*------------------ 验证订单产生的佣金是否正确。针对后来上线的带有佣金记录的 begin ---------------*/
		 	int sumCommisionFee=0;
		 	int hideCommisionFee=0;
		    ParamsCommisionVo commisionVo = new ParamsCommisionVo();
			commisionVo.setOrderObjectId(orderObj.getId());
			commisionVo.getBusinessTypeSet().add(1);//开店分佣
			commisionVo.getBusinessTypeSet().add(2);//直接分佣
			commisionVo.getBusinessTypeSet().add(3);//间接分佣
			List<Commision> CommisionLsit=commissionService.queryAll(commisionVo);
			
//			int calculationOpenCommisionSCount=0;
			//开店单不能没有佣金 和佣金记录 从2017-12-22 00:00:00
			if(orderObj.getOpenStore()==1&&(orderObj.getCommisionFee()==0||!ListUtils.isNotEmpty(CommisionLsit))
					&&StringUtils.compare(orderObj.getCreateTime(), "2017-12-22 00:00:00")>0){
				ResultMap.put("1",orderObj.getOrderSn());
				ResultMap.put("2", "该开店单没有分佣明细");
				return ResultMap;
			}
			if(orderObj.getCommisionFee()>0&&!ListUtils.isNotEmpty(CommisionLsit)){
				ResultMap.put("1",orderObj.getOrderSn());
				ResultMap.put("2", "该订单有分佣，但是没有分佣明细信息");
				return ResultMap;
			}
			if(orderObj.getCommisionFee()==0&&ListUtils.isNotEmpty(CommisionLsit)){
				boolean flag=false;
				for(Commision Commision:CommisionLsit){
					if(Commision.getFee()>0||(StringUtils.isNotBlank(Commision.getExtend3())&&Integer.parseInt(Commision.getExtend3())>0)){
						flag=true;
						break;
					}
				}
				if(flag){
					ResultMap.put("1",orderObj.getOrderSn());
					ResultMap.put("2", "该单没有分佣，但是有分佣明细");
					return ResultMap;
				}
			}
			//新的逻辑中 每笔订单只能拿一次开店分佣
			if(orderObj.getOpenStore()==1){
				for(Commision Commision:CommisionLsit){ 
					if(Commision.getFee()>=0){//不是售后负向
						//是开店产品 但没有开店分佣
						if(orderDetailMap.get(Commision.getOrderDetailId()).getIsOpenStoreGoods()==1
								&&!"开店分佣".equals(Commision.getComment())){
							ResultMap.put("1",orderObj.getOrderSn());
							ResultMap.put("2", "该开店单的开店产品没有开店分佣");
							return ResultMap;
						}
						//不是开店产品 但有开店分佣
						if(orderDetailMap.get(Commision.getOrderDetailId()).getIsOpenStoreGoods()!=1
								&&"开店分佣".equals(Commision.getComment())&&StringUtils.compare(Commision.getCreateTime(), "2018-01-16 00:00:00")>0){
							ResultMap.put("1",orderObj.getOrderSn());
							ResultMap.put("2", "该开店单的非开店产品有开店分佣");
							return ResultMap;
						}
						
					}
				}
			}
			if(orderObj.getOpenStore()==1&&StringUtils.compare(orderObj.getPayTime(),"2018-02-08 00:00:00")>0){//2018-02-08 00:00:00 之后的开店单
				long opensoreSum=0;
				for(Commision Commision:CommisionLsit){
					if(Commision.getFee()>=0){
						opensoreSum+=Commision.getFee().longValue()+
								(StringUtils.isNotBlank(Commision.getExtend3())?Long.parseLong(Commision.getExtend3()):0);
						if(NumberUtils.isNumber(Commision.getExtend1())&&StringUtils.isNotBlank(Commision.getExtend2())){
							//区分开店分佣和正常分佣 正常分佣单独校验
							//1. 开店分佣
							if("开店分佣".equals(Commision.getComment())&&StringUtils.contains(Commision.getExtend2(),"UserCommision")){
								UserCommision	UserCommision=
										JSONObject.parseObject(StringUtils.remove(
												Commision.getExtend2(),"UserCommision").replace('[','{').replace(']','}').replace('=',':').concat("}"),
												UserCommision.class);
								if(UserCommision.getShowCommisionFee()!=Commision.getFee().longValue()
										||Long.parseLong(Commision.getExtend3())!=UserCommision.getHideCommisionFee()){//校验分佣失败
									ResultMap.put("1",orderObj.getOrderSn());
									ResultMap.put("2", "该订单的商品分佣明细校验失败, 配置的分佣明细:"
									+Commision.getExtend2()+" 实际分佣 :"+Commision.getFee()+" 隐藏分佣:"+Commision.getExtend3());
									return ResultMap;
								}
							}
						}
					}
				}
				if(!(20000<=opensoreSum&&24000>=opensoreSum)){//异常分佣
					if(opensoreSum!=5000){
						ResultMap.put("1",orderObj.getOrderSn());
						ResultMap.put("2", "该开店单的分佣金额异常:"+opensoreSum);
						return ResultMap;
					}
				}
			}
			if(orderObj.getOpenStore()!=1&&StringUtils.compare(orderObj.getPayTime(),"2018-02-07 09:00:00")>0){//2018-02-07 09:00:00 之后的非开店单
				Map<Long,Integer> beginSum=new HashMap<Long,Integer>();
				for(Commision Commision:CommisionLsit){
					if(Commision.getFee()>=0&&beginSum.get(Commision.getOrderDetailId())==null){
						beginSum.put(Commision.getOrderDetailId(),Commision.getFee());
					}
				}
				for(Commision Commision:CommisionLsit){
					if(Commision.getFee()>=0){
						if(NumberUtils.isNumber(Commision.getExtend1())){//
							UserNormalCommision	UserNormalCommision=
									JSONObject.parseObject(StringUtils.remove(
									Commision.getExtend2(),"UserNormalCommision").replace('[','{').replace(']','}').replace('=',':').concat("}"),
									UserNormalCommision.class);
							  if(UserNormalCommision.isIshide()){
								  if(UserNormalCommision.getCommisionProportion()*beginSum.get(Commision.getOrderDetailId())/100!=
										  Long.parseLong(Commision.getExtend3()==null?"0":Commision.getExtend3())){
									  ResultMap.put("1",orderObj.getOrderSn());
										ResultMap.put("2", "该订单有分佣记录错误 ：实际分佣:"+Commision.getExtend3()+" 计算分佣:"
												+(UserNormalCommision.getCommisionProportion()*beginSum.get(Commision.getOrderDetailId())/100));
										return ResultMap;
								  }
							  }else{
								  if(UserNormalCommision.getCommisionProportion()*beginSum.get(Commision.getOrderDetailId())/100!=Commision.getFee()){
										ResultMap.put("1",orderObj.getOrderSn());
										ResultMap.put("2", "该订单有分佣记录错误：实际分佣:"+Commision.getExtend3()+" 计算分佣:"
												+(Commision.getFee()));
										return ResultMap;
								  }
							  }
						}
					}
				}
			}
			//验证产生的分佣 从2018-01-15 20:37:55开始
			for(Commision Commision:CommisionLsit){
				if(Commision.getFee()>0&&StringUtils.isBlank(Commision.getExtend2())&&
						StringUtils.compare(Commision.getCreateTime(),"2018-01-15 20:37:55")>0){//无记录分佣信息
					ResultMap.put("1",orderObj.getOrderSn());
					ResultMap.put("2", "该订单有分佣未记录分佣比例");
					return ResultMap;
				}
				
				//验证佣金合法性
				if(Commision.getFee()>0){//不是售后负向
					if(StringUtils.isNotBlank(Commision.getExtend2())){//有分佣记录 开始计算
						if(StringUtils.startsWith(Commision.getExtend2(),"LimitTimeSaleGoodsCommission")){//分时抢购分佣
							if(orderDetailMap.get(Commision.getOrderDetailId()).getLimitTimeSaleId()==0){
								ResultMap.put("1",orderObj.getOrderSn());
								ResultMap.put("2", "该订单的分佣产品不是分时抢购产品 产品名:"+orderDetailMap.get(Commision.getOrderDetailId()).getGoodName());
								return ResultMap;
							}
							//开始重新计算分佣
							LimitTimeSaleGoodsCommission	limitTimeSaleGoodsCommission=
						JSONObject.parseObject(StringUtils.remove(
						Commision.getExtend2(),"LimitTimeSaleGoodsCommission").replace('[','{').replace(']','}').replace('=',':'), LimitTimeSaleGoodsCommission.class);
							
							//分佣类型判断
							if(limitTimeSaleGoodsCommission.getCommissionType()!=1&&limitTimeSaleGoodsCommission.getCommissionType()!=2){//既不是比例 也不是金额
								ResultMap.put("1",orderObj.getOrderSn());
								ResultMap.put("2", "该订单的分佣计算类型异常:"+JsonUtil.toJson(limitTimeSaleGoodsCommission));
								return ResultMap;
							}
							
							if("直卖分佣".equals(Commision.getComment())){
								if(limitTimeSaleGoodsCommission.getCommissionType()==1&&
										(limitTimeSaleGoodsCommission.getCommission()*
										(orderDetailMap.get(Commision.getOrderDetailId()).getTotalFee()+orderDetailMap.get(Commision.getOrderDetailId()).getBalancePaid()
										+orderDetailMap.get(Commision.getOrderDetailId()).getCashCoin())/100)!=Commision.getFee()){//按照比例
									ResultMap.put("1",orderObj.getOrderSn());
									ResultMap.put("2","该订单特卖商品的直卖分佣校验失败 分佣事务ID:"+Commision.getId()+" 应记分佣金额:"+(limitTimeSaleGoodsCommission.getCommission()*
											(orderDetailMap.get(Commision.getOrderDetailId()).getTotalFee()+orderDetailMap.get(Commision.getOrderDetailId()).getBalancePaid()
													+orderDetailMap.get(Commision.getOrderDetailId()).getCashCoin())/100)+
											" 实际分佣金额:"+Commision.getFee());
									return ResultMap;
								}else if(limitTimeSaleGoodsCommission.getCommissionType()==2&&
								(limitTimeSaleGoodsCommission.getCommission()*orderDetailMap.get(Commision.getOrderDetailId()).getQuantity())!=Commision.getFee()){//按照金额
									ResultMap.put("1",orderObj.getOrderSn());
									ResultMap.put("2","该订单特卖商品的直卖分佣校验失败 分佣事务ID:"+Commision.getId()+" 应记分佣金额:"+(limitTimeSaleGoodsCommission.getCommission()*orderDetailMap.get(Commision.getOrderDetailId()).getQuantity())+
											" 实际分佣金额:"+Commision.getFee());
									return ResultMap;
								}
							}else if("间接分佣".equals(Commision.getComment())){
								if(limitTimeSaleGoodsCommission.getCommissionType()==1&&
										(limitTimeSaleGoodsCommission.getIndirectCommission()*
										(orderDetailMap.get(Commision.getOrderDetailId()).getTotalFee()+orderDetailMap.get(Commision.getOrderDetailId()).getBalancePaid()
										+orderDetailMap.get(Commision.getOrderDetailId()).getCashCoin())/100)!=Commision.getFee()){//按照比例
									ResultMap.put("1",orderObj.getOrderSn());
									ResultMap.put("2","该订单特卖商品的间接分佣校验失败 分佣事务ID:"+Commision.getId()+" 应记分佣金额:"+(limitTimeSaleGoodsCommission.getIndirectCommission()*
											(orderDetailMap.get(Commision.getOrderDetailId()).getTotalFee()+orderDetailMap.get(Commision.getOrderDetailId()).getBalancePaid()
													+orderDetailMap.get(Commision.getOrderDetailId()).getCashCoin())/100)+
											" 实际分佣金额:"+Commision.getFee());
									return ResultMap;
								}else if(limitTimeSaleGoodsCommission.getCommissionType()==2&&
								(limitTimeSaleGoodsCommission.getIndirectCommission()*orderDetailMap.get(Commision.getOrderDetailId()).getQuantity())!=Commision.getFee()){//按照金额
									ResultMap.put("1",orderObj.getOrderSn());
									ResultMap.put("2","该订单特卖商品的间接分佣校验失败 分佣事务ID:"+Commision.getId()+" 应记分佣金额:"+
									(limitTimeSaleGoodsCommission.getIndirectCommission()*orderDetailMap.get(Commision.getOrderDetailId()).getQuantity())+
											" 实际分佣金额:"+Commision.getFee());
									return ResultMap;
								}
							}
						}else if(StringUtils.startsWith(Commision.getExtend2(),"GoodsCommission")){//正常商品分佣
							
							if(orderDetailMap.get(Commision.getOrderDetailId()).getLimitTimeSaleId()!=0){
								ResultMap.put("1",orderObj.getOrderSn());
								ResultMap.put("2", "该订单的分佣产品是分时抢购产品不是普通产品 产品名:"+orderDetailMap.get(Commision.getOrderDetailId()).getGoodName());
								return ResultMap;
							}
							//开始重新计算分佣
							GoodsCommission	GoodsCommission=
									JSONObject.parseObject(StringUtils.remove(
											Commision.getExtend2(),"GoodsCommission").replace('[','{').replace(']','}').replace('=',':'), GoodsCommission.class);
							
							//分佣类型判断
							if(GoodsCommission.getCommissionType()!=1&&GoodsCommission.getCommissionType()!=2){//既不是比例 也不是金额
								ResultMap.put("1",orderObj.getOrderSn());
								ResultMap.put("2", "该订单的分佣计算类型异常:"+JsonUtil.toJson(GoodsCommission));
								return ResultMap;
							}
							
							 if("开店分佣".equals(Commision.getComment())&&
									((GoodsCommission.getOpenStoreCommission()*orderDetailMap.get(Commision.getOrderDetailId()).getQuantity())!=Commision.getFee().intValue())){
								ResultMap.put("1",orderObj.getOrderSn());
								ResultMap.put("2", "该订单的开店分佣校验失败 分佣事务ID:"+Commision.getId()+" 应记分佣金额:"+(GoodsCommission.getOpenStoreCommission()*orderDetailMap.get(Commision.getOrderDetailId()).getQuantity())+
										" 实际分佣金额:"+Commision.getFee());
								return ResultMap;
							}else if("直卖分佣".equals(Commision.getComment())){
								if(GoodsCommission.getCommissionType()==1&&
										(GoodsCommission.getCommission()*
										(orderDetailMap.get(Commision.getOrderDetailId()).getTotalFee()+orderDetailMap.get(Commision.getOrderDetailId()).getBalancePaid()
										+orderDetailMap.get(Commision.getOrderDetailId()).getCashCoin())/100)!=Commision.getFee()){//按照比例
									ResultMap.put("1",orderObj.getOrderSn());
									ResultMap.put("2","该订单的直卖分佣校验失败 分佣事务ID:"+Commision.getId()+" 应记分佣金额:"+(GoodsCommission.getCommission()*
											(orderDetailMap.get(Commision.getOrderDetailId()).getTotalFee()+orderDetailMap.get(Commision.getOrderDetailId()).getBalancePaid()
													+orderDetailMap.get(Commision.getOrderDetailId()).getCashCoin())/100)+
											" 实际分佣金额:"+Commision.getFee());
									return ResultMap;
								}else if(GoodsCommission.getCommissionType()==2&&
								(GoodsCommission.getCommission()*orderDetailMap.get(Commision.getOrderDetailId()).getQuantity())!=Commision.getFee()){//按照金额
									ResultMap.put("1",orderObj.getOrderSn());
									ResultMap.put("2","该订单的直卖分佣校验失败 分佣事务ID:"+Commision.getId()+" 应记分佣金额:"+(GoodsCommission.getCommission()*orderDetailMap.get(Commision.getOrderDetailId()).getQuantity())+
											" 实际分佣金额:"+Commision.getFee());
									return ResultMap;
								}
							}else if("间接分佣".equals(Commision.getComment())){
								if(GoodsCommission.getCommissionType()==1&&
										(GoodsCommission.getIndirectCommission()*
										(orderDetailMap.get(Commision.getOrderDetailId()).getTotalFee()+orderDetailMap.get(Commision.getOrderDetailId()).getBalancePaid()
										+orderDetailMap.get(Commision.getOrderDetailId()).getCashCoin())/100)!=Commision.getFee()){//按照比例
									ResultMap.put("1",orderObj.getOrderSn());
									ResultMap.put("2","该订单的直卖分佣校验失败 分佣事务ID:"+Commision.getId()+" 应记分佣金额:"+(GoodsCommission.getIndirectCommission()*
											(orderDetailMap.get(Commision.getOrderDetailId()).getTotalFee()+orderDetailMap.get(Commision.getOrderDetailId()).getBalancePaid()
													+orderDetailMap.get(Commision.getOrderDetailId()).getCashCoin())/100)+
											" 实际分佣金额:"+Commision.getFee());
									return ResultMap;
								}else if(GoodsCommission.getCommissionType()==2&&
								(GoodsCommission.getIndirectCommission()*orderDetailMap.get(Commision.getOrderDetailId()).getQuantity())!=Commision.getFee()){//按照金额
									ResultMap.put("1",orderObj.getOrderSn());
									ResultMap.put("2","该订单的直卖分佣校验失败 分佣事务ID:"+Commision.getId()+" 应记分佣金额:"+(GoodsCommission.getIndirectCommission()*orderDetailMap.get(Commision.getOrderDetailId()).getQuantity())+
											" 实际分佣金额:"+Commision.getFee());
									return ResultMap;
								}
							}
						}else if(NumberUtils.isNumber(Commision.getExtend1())){//是数字 2月7号版本的分佣规则
							//区分开店分佣和正常分佣 正常分佣单独校验 不在这里验证单独验证
						}else{//未找到的类型
							ResultMap.put("1",orderObj.getOrderSn());
							ResultMap.put("2", "该订单的商品分佣明细未找到,异常分佣明细:"+Commision.getExtend2());
							return ResultMap;
						}
					}
					sumCommisionFee+=Commision.getFee();
				}
			}
			//之前的旧开店订单不进行验证
			if(orderObj.getCommisionFee()!=sumCommisionFee){//订单分佣和分佣明细不一致
				boolean check=true;
				if(orderObj.getOpenStore()==1&&
					StringUtils.compare(orderObj.getCreateTime(),"2018-01-15 19:21:37")<0){
					check=false;
				}
				if(check){
					ResultMap.put("1",orderObj.getOrderSn());
					ResultMap.put("2", "该订单的分佣记录异常: 订单分佣金额:"+orderObj.getCommisionFee()+" 分佣明细总额"+sumCommisionFee);
					return ResultMap;
				}
			}
			/*------------------验证订单产生的佣金是否正确。针对后来上线的带有佣金记录的 end---------------*/
			
		//验证订单的推送状态
		if(orderObj.getStatus()==2&&orderObj.getHandleStatus()!=1){//订单未推送
			//查询推送失败原因
			XzOmsLog log=xzOmsLogService.selectAutoPushOrderByOrderSn(orderObj.getOrderSn());
			ResultMap.put("1",orderObj.getOrderSn());
			ResultMap.put("2", "该订单还未推送到oms"+(log!=null?" ,失败原因: "+log.getResult():""));
			  return ResultMap;
		}
	//2.订单状态为4到6 说明用户由待评价到完成状态 这个时候订单上的分佣应该都是处理掉的	
		if(orderObj.getStatus()==6){
			//查询所有分佣信息 
			ParamsCommisionVo paramsCommisionVo = new ParamsCommisionVo();
			paramsCommisionVo.setStatus(1);
			paramsCommisionVo.setResult(1);
			paramsCommisionVo.setOrderObjectId(orderObj.getId());
			paramsCommisionVo.getBusinessTypeSet().add(1);//开店分佣
			paramsCommisionVo.getBusinessTypeSet().add(2);//直接分佣
			paramsCommisionVo.getBusinessTypeSet().add(3);//间接分佣
			paramsCommisionVo.getBusinessTypeSet().add(17);//其他角色分佣
			List<Commision> commisionList = commissionService.queryAll(paramsCommisionVo);//查找所有的处理过的分佣
			//积分事务
			ParamsUserXzbTransactionVo params_user_xzb_transaction=new ParamsUserXzbTransactionVo();
			params_user_xzb_transaction.setTransactionStatus(1);
			params_user_xzb_transaction.getBusinessTypeSet().add(12);//消费送妆币
			params_user_xzb_transaction.setBusinessSourceId(orderObj.getId());
		  List<CUserPointTransaction> CUserPointTransactionList=
				 cUserPointTransactionService.queryAll(params_user_xzb_transaction);
		  Map<Long,CUserPointTransaction>  CUserPointTransactionMap=new HashMap<Long,CUserPointTransaction>();
			Map<Long,Commision>  CommisionMap=new HashMap<Long,Commision>();
			for(OrderDetail d:listorderDetail){
				if(d.getStatus()==6||d.getStatus()==7){
			        for(Commision c:commisionList){
			        	if(c.getOrderDetailId().longValue()==d.getId().longValue()){
			        		CommisionMap.put(c.getId(), c);
			        	}
			        }
			        for(CUserPointTransaction c:CUserPointTransactionList){
			        	if(c.getOrderDetailId().longValue()==d.getId().longValue()){
			        		CUserPointTransactionMap.put(c.getId(), c);
			        	}
			        }	
				}
			}
			if(commisionList!=null&&commisionList.size()>0&&CommisionMap.size()!=commisionList.size()){
				 ResultMap.put("1",orderObj.getOrderSn());
				 ResultMap.put("2", "完成单和订单已处理的佣金事务不符");
				  return ResultMap;
			}
			if(CUserPointTransactionList!=null&&CUserPointTransactionList.size()>0&&CUserPointTransactionMap.size()!=CUserPointTransactionList.size()){
				 ResultMap.put("1",orderObj.getOrderSn());
				 ResultMap.put("2", "完成单和订单已处理的妆币事务不符");
				  return ResultMap;
			}
			//验证分佣产生的流水
			for(Commision  commision:commisionList){
				List<UserJournal> UserJournalList=
					userJournalMapper.selectJournalByCommisionId(commision.getId().intValue());
			   if(UserJournalList!=null&&UserJournalList.size()>1){
				   ResultMap.put("1",orderObj.getOrderSn());
				   ResultMap.put("2", "订单余额流水重复");
					  return ResultMap;
			   }
			   if(UserJournalList==null||UserJournalList.size()==0){
				   ResultMap.put("1", orderObj.getOrderSn());
				   ResultMap.put("2", "未找到该余额事务的流水");
					  return ResultMap;
			   }
			   if(UserJournalList.get(0).getBusinessTypeId()!=commision.getBusinessTypeId().intValue()){
				   ResultMap.put("1",orderObj.getOrderSn());
				   ResultMap.put("2", "余额流水和余额事务的记账类型不同");
					  return ResultMap;
			   }
			   if(("+".equals(UserJournalList.get(0).getType())?UserJournalList.get(0).getMoney():0-UserJournalList.get(0).getMoney())!=commision.getFee().intValue()){
				   ResultMap.put("1",orderObj.getOrderSn());
				   ResultMap.put("2", "余额事务和相应流水的金额不一致 commisionID:"+commision.getId()+" UserJournalID："+UserJournalList.get(0).getId());
				   return ResultMap;
			   }
			}
			//验证妆币产生的流水
			for(CUserPointTransaction  CUserPointTransaction:CUserPointTransactionList){
				List<UserPointJournal> UserPointJournalList=
						userPointJournalMapper.selectBySourceIDBusinessType(CUserPointTransaction.getId(), CUserPointTransaction.getBusinessTypeId());
				if(UserPointJournalList!=null&&UserPointJournalList.size()>1){
					 ResultMap.put("1",orderObj.getOrderSn());
					 ResultMap.put("2", "订单妆币流水重复");
					  return ResultMap;
				}
				if(UserPointJournalList==null||UserPointJournalList.size()==0){
					 ResultMap.put("1",orderObj.getOrderSn());
					 ResultMap.put("2", "未找到该妆币事务的流水");
					  return ResultMap;
				}
				if(UserPointJournalList.get(0).getAmount().longValue()!=CUserPointTransaction.getAmount().longValue()){
					 ResultMap.put("1",orderObj.getOrderSn());
					 ResultMap.put("2", "该妆币事务和相应流水  金额不一致");
					  return ResultMap;
				}
			}
		}
		return null;
	}

	@Override
	public boolean isFirstOrder(Long userId) {
		String key = RedisKeys.ORDER_FIRST_USER + userId;
		boolean exists = redisUtil.exists(key);
		if (exists) {//存在缓存
			String string = redisUtil.get(key);
			if (StringUtils.equals("0", string)) {//不是首单用户
				return false;
			}
		}
		int a = orderDao.selectCountByStatus(userId, 2);
		int b= orderDao.selectCountByStatus(userId, 3);
		b += orderDao.selectCountByStatus(userId, 4);
		b += orderDao.selectCountByStatus(userId, 6);
		b += orderDao.selectCountByStatus(userId, 7);
		if (b >= 1 || a > 1) {//存在有效订单，不是首单
			redisUtil.set(key, "0");
			return false;
		}
		return true;
	}

}
